package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.scwatch.common.orm.LimitRequest;
import com.scwatch.common.orm.Limitable;
import com.scwatch.common.orm.RowSide;
import com.scwatch.common.util.Dates;
import com.scwatch.common.util.RequestUtils;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.fulltext.InfoFulltextService;
import com.scwatch.core.html.HtmlGenerator;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.CmsException;
import com.scwatch.core.support.Context;
import com.scwatch.ext.domain.LiveBroadcast;
import com.scwatch.ext.service.LiveBroadcastService;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.tools.ant.util.DateUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.scwatch.core.constant.Constants.*;

/**
 * 栏目管理（发布中心）栏目、新闻 新建等功能
 *
 * @author gjl
 *
 */
@Controller
@RequestMapping("/core/pub_center")
public class PublishCenterController {
	private static final Logger logger = LoggerFactory.getLogger(PublishCenterController.class);

    public static final int INCLUDE_CHILDREN = 0;
    public static final int INCLUDE_MULTI = 1;
    public static final int MAIN_NODE = 2;

    /**
     * 左侧栏目树形菜单
     * @param request 页面参数
     * @param modelMap 结果页面
     * @return
     */
	@RequiresPermissions(value = {
	        "core:site:list",
	        "core:pub_center:list",
    },logical = Logical.OR)
	@RequestMapping("left.do")
	public String left(HttpServletRequest request, org.springframework.ui.Model modelMap) {
        User user = Context.getCurrentUser();
        Integer siteId = Context.getCurrentSiteId();
        Integer treeLevel=3;
        List<Node> nodeList = nodeQuery.findList(siteId,null,treeLevel,true, false);
        //报料 爬虫文库 草稿箱 不展示在栏目列表 单独菜单
        List<Node> removelist=new ArrayList<>();
        if(nodeList!=null&& nodeList.size()>0){
            for(Node node:nodeList){
               if(Constants.MODEL_FLAG_DRAFTS_NODE.equals(node.getNodeModel().getFlag())
                       || Constants.CRAWLER_LIBRARY.equals(node.getNodeModel().getFlag())
                       ||Constants.MODEL_FLAG_BAO.equals(node.getNodeModel().getFlag())
                       ||Constants.MODEL_Back_to_see_date.equals(node.getNodeModel().getFlag())
                       ||Constants.MODEL_Back_to_see_program.equals(node.getNodeModel().getFlag())
                       ||Constants.MODEL_program_keyword_management.equals(node.getNodeModel().getFlag())){
                   removelist.add(node);
               }
            }
            nodeList.removeAll(removelist);
        }

        nodeList = user.getNodePermList(siteId, nodeList);
        modelMap.addAttribute("nodeList", nodeList);
		return "core/publish_center/publish_center_left";
	}

    /**
     * 不同栏目跳转不同页面
     * @param queryNodeId 栏目id
     * @param showDescendants 显示子栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param pageable 分页对象
     * @param request 页面参数
     * @param modelMap
     * @param ra
     * @return 重定向字符串
     */
    @RequiresPermissions("core:site:forward")
    @RequestMapping("forward.do")
    public String forward(Integer queryNodeId, @RequestParam(defaultValue = "true") boolean showDescendants,
                          Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                       @PageableDefault(sort = {"publishDate", "id"},direction = Sort.Direction.DESC) Pageable pageable,
                          HttpServletRequest request, org.springframework.ui.Model modelMap,RedirectAttributes ra) {

	    User user = Context.getCurrentUser();
        Integer siteId = Context.getCurrentSiteId();
        Node node=null;
        Model nodeModel=new Model();
        if(queryNodeId!=null){
             node=nodeQuery.get(queryNodeId);
             nodeModel=node.getModel();
        }

            //判断 栏目模型标记 是哪种，例如焦点，直播
            //1焦点
        String url="";
        if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_FOCUS.equals(nodeModel.getFlag())){
            url="redirect:focuslist.do";
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("queryNodeType","0");
            ra.addAttribute("returnUrl","core/publish_center/focus_list");
            //2直播
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_LIVE.equals(nodeModel.getFlag())){
            ra.addAttribute("queryNodeId",queryNodeId);
            url="redirect:/cmscp/core/livenode/selectlivelist.do";
            //3热门视频
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_HOTVIDEO.equals(nodeModel.getFlag())){
            url="redirect:infolist.do";
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("queryNodeType","0");
            //24小时要闻
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_24HOURSNEWS.equals(nodeModel.getFlag())) {

            ra.addAttribute("queryNodeId", queryNodeId);
            ra.addAttribute("returnUrl", "core/current_hour/hour_list");
            url = "redirect:/cmscp/core/current_hour/list.do";
            //滚动资讯
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_SCROLLINFO.equals(nodeModel.getFlag())){
            ra.addAttribute("queryNodeId", queryNodeId);
            url = "redirect:/cmscp/core/flash_big/flash_big_list.do";
            //时讯
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_CURRENTNEWS.equals(nodeModel.getFlag())){
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("returnUrl","core/current_hour/currentnews_list");
            url="redirect:/cmscp/core/current_hour/list.do";
            //直播栏目
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_FLAG_LIVE_NODE.equals(nodeModel.getFlag())){
            ra.addAttribute("queryNodeId",queryNodeId);
            url="redirect:/cmscp/core/livenode/livelist.do";
            //主播栏目
        } else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_FLAG_ANCHOR_NODE.equals(nodeModel.getFlag())){
            url="core/publish_center/anchor_node_list";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init","0");
            //主播栏目详情
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(nodeModel.getFlag())){
//            url="core/publish_center/anchor_node_detail_list";
//            modelMap.addAttribute("queryParentId", queryNodeId);
//            modelMap.addAttribute("showDescendants", showDescendants);
//            modelMap.addAttribute("init","0");
            url="redirect:infolist.do";
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("queryNodeType","0");
            //原创资讯
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_ORIGINAL_INFO.equals(nodeModel.getFlag())){
            url="core/publish_center/originalnfo_node_list";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init","0");
            //主播动态
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_ANCHOR_DYNAMIC.equals(nodeModel.getFlag())){
            url="core/publish_center/dynamic_node_list";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init","0");
            //主播圈动态
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(nodeModel.getFlag())) {
            url = "core/publish_center/dynamic_info_list";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //卫视
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.MODEL_FLAG_SCTV.equals(nodeModel.getFlag())) {
            url = "redirect:/cmscp/core/sinatv/list.do";
            modelMap.addAttribute("queryNodeId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //专题
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.SPECIAL_MANAGEMENT.equals(nodeModel.getFlag())) {
            url = "redirect:/cmscp/core/special/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //专题类别
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.SPECIAL_CATEGORY.equals(nodeModel.getFlag())) {
                url = "redirect:/cmscp/core/special_category/list.do";
                modelMap.addAttribute("queryParentId", queryNodeId);
                modelMap.addAttribute("showDescendants", showDescendants);
                modelMap.addAttribute("init", "0");
            //专题回收站
        }else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                Constants.SPECIAL_RECYCLE.equals(nodeModel.getFlag())) {
            url = "redirect:/cmscp/core/special_recycle/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //爬虫文库
        }
        else if(StringUtils.isNotBlank(nodeModel.getFlag()) &&
                    Constants.CRAWLER_LIBRARY.equals(nodeModel.getFlag())) {
            url="redirect:infolist.do";
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("returnUrl","crawler_info_list");
            ra.addAttribute("queryNodeType","0");
          //节目回看
        }
        else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_TV_of_yesterday.equals(nodeModel.getFlag())){
            url="redirect:/cmscp/core/programback/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //回看日期选择
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_Back_to_see_date.equals(nodeModel.getFlag())){
            url="redirect:/cmscp/core/programDatecheck/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //回看节目单
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_Back_to_see_program.equals(nodeModel.getFlag())){
            url="redirect:/cmscp/core/programbackcode/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //节目关键词管理
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_program_keyword_management.equals(nodeModel.getFlag())){
            url="redirect:/cmscp/core/program/list.do";
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");
            //市州
            } else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                    Constants.MODEL_FLAG_CITY_STATE.equals(nodeModel.getFlag())){
             url="redirect:citynodelist.do";
             ra.addAttribute("queryParentId", queryNodeId);
             ra.addAttribute("showDescendants", showDescendants);
            //活动
        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_FLAG_ACTIVITY_NODE.equals(nodeModel.getFlag())){
            url="redirect:infolist.do";
            ra.addAttribute("queryNodeId",queryNodeId);
            ra.addAttribute("queryNodeType","0");
            ra.addAttribute("returnUrl","info_activity_list");

        }else if(StringUtils.isNotBlank(nodeModel.getFlag())&&
                Constants.MODEL_FLAG_GC.equals(nodeModel.getFlag())){
            url = "redirect:/cmscp/core/gc/list.do";
            modelMap.addAttribute("queryNodeId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init", "0");

        }else if(node!=null && (node.getChildren()==null|| node.getChildren().size()==0 )){
              url="redirect:infolist.do";
              ra.addAttribute("queryNodeId",queryNodeId);
              ra.addAttribute("queryNodeType","0");
        }else{
            modelMap.addAttribute("queryParentId", queryNodeId);
            modelMap.addAttribute("showDescendants", showDescendants);
            modelMap.addAttribute("init","0");
            modelMap.addAttribute("returnUrl","nodelist");
            url="core/publish_center/node_list";
        }
        return url;
    }

    /**
     * 主播栏目
     * @param queryParentId 父栏目id
     * @param showDescendants 显示子栏目
     * @param pageable 分页对象
     * @param request
     * @param modelMap
     * @return 结果页面
     */

//    @RequiresPermissions("core:anchor:list")
    @RequestMapping("anchorlist.do")
    public String anchorlist(Integer queryParentId,@RequestParam(defaultValue = "true") boolean showDescendants,
                       @PageableDefault(sort = { "treeNumber", "id" }, direction = Sort.Direction.ASC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Node parent = null;
        if (queryParentId != null) {
            parent = nodeQuery.get(queryParentId);
        }
        if (parent == null) {
            parent = nodeQuery.findRoot(siteId);
            if (parent != null) {
                queryParentId = parent.getId();
            }
        }
        String treeNumber = null;
        if (showDescendants && parent != null) {
            treeNumber = parent.getTreeNumber();
        }
        String name=request.getParameter("search_CONTAIN_name");
        Integer[] sites=new Integer[]{siteId};
        Page<Node>  pagedList= nodeQuery.findPage(sites, queryParentId,treeNumber,true,false, null,
                null,null,null,null,null,null,
                pageable,name,null);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("pagedList", pagedList);
        return "core/publish_center/anchor_node_list";
    }


//    @RequiresPermissions("core:anchor_node_detail:list")
    @RequestMapping("anchor_node_detail_list.do")
    public String anchor_node_detail_list(Integer queryParentId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                       @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryParentId != null) {
            queryNode = nodeQuery.get(queryParentId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryParentId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryParentId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        String[] treeNumbers=null;
        if(treeNumber!=null){
            treeNumbers=new String[]{treeNumber.toString()};
        }
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
//        Page<Info> pagedList = infoQuery.findAll(siteId, mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
//                infoPermType, queryStatus, params, pageable,null);
        Page<Info> pagedList = infoQuery.findPage(null,new Integer[]{nodeId},null,
                null, null,new Integer[]{siteId},new Integer[]{mainNodeId} ,new Integer[]{user.getId()}, null,
                null,treeNumbers, null, null, null,
                null, null, null, null, null,
                null, null, null,new String[]{queryStatus},null, null,
                null, null, null, null, null, null, pageable,null,null,null,null);
        List<Attribute> attributeList = attributeService.findList(siteId);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node", queryNode);
        return "core/publish_center/anchor_node_detail_list";
    }

    /**
     * 栏目查询
     * @param queryParentId 父栏目id
     * @param returnUrl 返回url
     * @param showDescendants 显示子栏目
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:node:list")
    @RequestMapping("nodelist.do")
    public String nodelist(Integer queryParentId,String returnUrl, @RequestParam(defaultValue = "true") boolean showDescendants,
                       @PageableDefault(sort = { "treeNumber", "id" }, direction = Sort.Direction.ASC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        User user = Context.getCurrentUser();
        Integer siteId = Context.getCurrentSiteId();
        Node parent = null;
        if (queryParentId != null) {
            parent = nodeQuery.get(queryParentId);
        }
        if (parent == null) {
            parent = nodeQuery.findRoot(siteId);
            if (parent != null) {
                queryParentId = parent.getId();
            }
        }
        String treeNumber = null;
        if (showDescendants && parent != null) {
            treeNumber = parent.getTreeNumber();
        }
        boolean isAllNodePerm = user.getAllNodePerm(siteId);
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Integer treeLevel=2;
        List<Node> list = nodeQuery.findList(siteId, treeNumber,queryParentId, user.getId(), isAllNodePerm, params,
                pageable.getSort());
        List<Model> nodeModelList = modelService.findList(siteId, Node.NODE_MODEL_TYPE);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("list", list);
        modelMap.addAttribute("nodeModelList", nodeModelList);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("showDescendants", showDescendants);
        modelMap.addAttribute("returnUrl",returnUrl);
        return "core/publish_center/node_list";
    }

    /**
     * 跳转到创建栏目页面
     * @param cid 栏目id
     * @param parentId 父栏目id
     * @param returnUrl 返回url
     * @param modelId 模型id
     * @param infoModelId 新闻模型id
     * @param queryParentId 父栏目id
     * @param showDescendants 显示子栏目
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:publish_center:create"
    },logical = Logical.OR)
    @RequestMapping("nodecreate.do")
    public String nodecreate(Integer cid, Integer parentId,String returnUrl,Integer modelId, Integer infoModelId, Integer queryParentId,
                         Boolean showDescendants, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        Integer siteId = site.getId();
        // 复制节点
        Node bean = null;
        if (cid != null) {
            bean = nodeQuery.get(cid);
            Backends.validateDataInSite(bean, siteId);
        }
        // 父节点
        Node parent = null;
        if (bean != null) {
            parent = bean.getParent();
        } else if (parentId != null) {
            parent = nodeQuery.get(parentId);
        } else {
            parent = nodeQuery.findRoot(siteId);
        }

        // 模型
        Model model = null;
        if (modelId != null) {
            // 指定模型
            model = modelService.get(modelId);
        } else if (bean != null) {
            // 复制节点
            model = bean.getNodeModel();
        } else if (parent != null && parent.getParent() != null) {
            // 指定了父节点，且父节点不是根节点。
            model = parent.getNodeModel();
        } else if (nodeQuery.findRoot(siteId) != null) {
            // 根节点存在，获取默认节点模型
            model = modelService.findDefault(siteId, Node.NODE_MODEL_TYPE);
            // 没有定义节点模型
            if (model == null) {
                throw new CmsException("node.error.nodeModelNotFound");
            }
        } else {
            // 根节点不存在，获取默认首页模型
            model = modelService.findDefault(siteId, Node.HOME_MODEL_TYPE);
            // 没有定义首页模型
            if (model == null) {
                throw new CmsException("node.error.nodeHomeModelNotFound");
            }
        }
        // 权限、信息模型
        if (parent != null && bean == null) {
            bean = new Node();
            bean.setNodeRoles(parent.getNodeRoles());
            bean.setNodeGroups(parent.getNodeGroups());
            bean.setNodeOrgs(parent.getNodeOrgs());
        }
        //主播栏目详情，需要加载主播数据(关联主播)
//        if(StringUtils.isNotBlank(model.getFlag()) &&
//                Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(model.getFlag())){
//            Map<String,String[]> paramMap=new HashMap<String,String[]>();
//            paramMap.put("EQ_flag",new String[]{Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS});
//            List<Model> models=modelService.findList(site.getId(),null,paramMap,null);
//
//
//            paramMap=new HashMap<String,String[]>();
//            String[] ids;
//            if(models!=null && models.size()>0){
//                ids=new String[models.size()];
//                for(int i=0;i<models.size();i++){
//                    ids[i]=models.get(i).getId().toString();
//                }
//                paramMap.put("EQ_nodeModel.id",ids);
//            }
//
//            Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
//            List<Node>  anchorNodeList=nodeQuery.findList(site.getId(),null,
//                    null,null,true,
//                    paramMap, paramSort);
//
//            modelMap.addAttribute("anchorNodeList", anchorNodeList);
//        }

        List<Role> roleList = roleService.findList(siteId);
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();
        String modelType = model.getType();
        List<Model> nodeModelList = modelService.findList(siteId, modelType);
        List<Model> infoModelList = modelService.findList(siteId, Info.MODEL_TYPE);
        Model infoModel = null;
        if (infoModelId != null) {
            infoModel = modelService.get(infoModelId);
        } else if (bean != null && bean.getInfoModel() != null) {
            infoModel = bean.getInfoModel();
        } else if (parent != null) {
            infoModel = parent.getInfoModel();
        } else if (!infoModelList.isEmpty()) {
            infoModel = infoModelList.get(0);
        }
        List<Workflow> workflowList = workflowService.findList(siteId);
        Node rootNode=null;
        if(parent!=null ){
            String flag=null;
            String docFlag=null;
            if(Constants.MODEL_FLAG_ANCHOR_NODE.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
            }else if(Constants.MODEL_FLAG_ANCHOR_DYNAMIC.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS;
                docFlag=Constants.MODEL_FLAG_DOC_DYNAMIC;
            }else if(Constants.MODEL_FLAG_CITY_STATE.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_CITY_DETAIL;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
            }else{
                //新建普通栏目，还可以新建活动栏目
//                flag=Constants.MODEL_FLAG_NEWS;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
                rootNode=  nodeQuery.findRoot(siteId);
                parent=rootNode;
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                paramMap.put("IN_flag",new String[]{Constants.MODEL_FLAG_NEWS,Constants.MODEL_FLAG_ACTIVITY_NODE});
                nodeModelList=modelService.findList(siteId,null,paramMap,null);
            }
            if(flag!=null){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                paramMap.put("EQ_flag",new String[]{flag});
                nodeModelList=modelService.findList(siteId,null,paramMap,null);
            }
            if(docFlag!=null){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                paramMap.put("EQ_flag",new String[]{docFlag});
                infoModelList=modelService.findList(siteId,null,paramMap,null);
            }
            if(Constants.MODEL_FLAG_ANCHOR.equals(parent.getNodeModel().getFlag())){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                flag=Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL;
                paramMap.put("EQ_flag",new String[]{flag});
                List<Model> list=modelService.findList(siteId,null,paramMap,null);
                flag=Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS;
                paramMap.put("EQ_flag",new String[]{flag});
                nodeModelList=modelService.findList(siteId,null,paramMap,null);
                nodeModelList.addAll(list);
            }
            if(nodeModelList!=null && nodeModelList.size()>0){
                boolean isDefault=true;
                for (Model m:nodeModelList){
                        if(model.getId().intValue()==m.getId().intValue()){
                               model=m;
                               isDefault=false;
                               break;
                        }
                }
                if(isDefault){
                    model=nodeModelList.get(0);
                }
            }

        }

        modelMap.addAttribute("workflowList", workflowList);
        modelMap.addAttribute("cid", cid);
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("model", model);
        modelMap.addAttribute("roleList", roleList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("nodeModelList", nodeModelList);
        modelMap.addAttribute("infoModel", infoModel);
        modelMap.addAttribute("infoModelList", infoModelList);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("showDescendants", showDescendants);
        modelMap.addAttribute(OPRT, CREATE);
        modelMap.addAttribute("returnUrl",returnUrl);
        return "core/publish_center/node_form";
    }

    /**
     * 跳转到编辑栏目页面
     * @param id 栏目id
     * @param modelId 模型
     * @param queryParentId 父栏目id
     * @param returnUrl 返回url
     * @param showDescendants 显示子栏目
     * @param position
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:publish_center:edit"
    },logical = Logical.OR)
    @RequestMapping("nodeedit.do")
    public String nodeedit(Integer id, Integer modelId, Integer queryParentId,String returnUrl,
                       @RequestParam(defaultValue = "false") boolean showDescendants, Integer position, @PageableDefault(sort = {
            "treeNumber", "id" }, direction = Sort.Direction.ASC) Pageable pageable, HttpServletRequest request,
                       org.springframework.ui.Model modelMap) {
        User user = Context.getCurrentUser();
        Site site = Context.getCurrentSite();
        Integer siteId = site.getId();
        Node bean = nodeQuery.get(id);
        Backends.validateDataInSite(bean, siteId);
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Node parent = bean.getParent();
        String treeNumber = null;
        if (showDescendants && parent != null) {
            treeNumber = parent.getTreeNumber();
        }
        boolean isAllNodePerm = user.getAllNodePerm(siteId);
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        RowSide<Node> side = nodeQuery.findSide(siteId, treeNumber, queryParentId, user.getId(), isAllNodePerm, params,
                bean, position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        List<Model> infoModelList = modelService.findList(siteId, Info.MODEL_TYPE);
        List<Model> modelList = modelService.findList(siteId, Node.NODE_MODEL_TYPE);
        List<Model> nodeModelList;
        if (bean.getParent() == null) {
            // 首页模型
            nodeModelList = modelService.findList(siteId, Node.HOME_MODEL_TYPE);
        } else {
            nodeModelList = modelList;
        }
        Model model;
        // 允许修改栏目模型
        if (modelId != null) {
            model = modelService.get(modelId);
        } else {
            model = bean.getNodeModel();
        }

//        //主播栏目详情，需要加载主播数据(关联主播)
//        if(StringUtils.isNotBlank(model.getFlag()) &&
//                Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(model.getFlag())){
//            Map<String,String[]> paramMap=new HashMap<String,String[]>();
//            paramMap.put("EQ_flag",new String[]{Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS});
//            List<Model> models=modelService.findList(site.getId(),null,paramMap,null);
//
//            paramMap=new HashMap<String,String[]>();
//            String[] ids;
//            if(models!=null && models.size()>0){
//                ids=new String[models.size()];
//                for(int i=0;i<models.size();i++){
//                    ids[i]=models.get(i).getId().toString();
//                }
//                paramMap.put("EQ_nodeModel.id",ids);
//            }
//
//            Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
//            List<Node>  anchorNodeList=nodeQuery.findList(site.getId(),null,
//                    null,null,true,
//                    paramMap, paramSort);
//
//            modelMap.addAttribute("anchorNodeList", anchorNodeList);
//        }

        List<Role> roleList = roleService.findList(siteId);
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();
        List<Workflow> workflowList = workflowService.findList(siteId);
        modelMap.addAttribute("workflowList", workflowList);
        List<UserMemberGroup> anchorUserList=userMemberGroupService.findListByParam(null,new Integer[]{5});

        if(parent!=null ){
            String flag=null;
            String docFlag=null;
            if(Constants.MODEL_FLAG_ANCHOR_NODE.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
            }else if(Constants.MODEL_FLAG_ANCHOR_DYNAMIC.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS;
                docFlag=Constants.MODEL_FLAG_DOC_DYNAMIC;
            }else if(Constants.MODEL_FLAG_CITY_STATE.equals(parent.getNodeModel().getFlag())){
                flag=Constants.MODEL_FLAG_CITY_DETAIL;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
            }else{
                flag=Constants.MODEL_FLAG_NEWS;
                docFlag=Constants.MODEL_FLAG_DOC_NEWS;
            }
            if(flag!=null){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                paramMap.put("EQ_flag",new String[]{flag});
                nodeModelList=modelService.findList(siteId,null,paramMap,null);
            }
            if(docFlag!=null){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                paramMap.put("EQ_flag",new String[]{docFlag});
                infoModelList=modelService.findList(siteId,null,paramMap,null);
            }
            if(Constants.MODEL_FLAG_ANCHOR.equals(parent.getNodeModel().getFlag())){
                Map<String,String[]> paramMap=new HashMap<String,String[]>();
                flag=Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL;
                paramMap.put("EQ_flag",new String[]{flag});
                List<Model> list=modelService.findList(siteId,null,paramMap,null);
                flag=Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS;
                paramMap.put("EQ_flag",new String[]{flag});
                nodeModelList=modelService.findList(siteId,null,paramMap,null);
                nodeModelList.addAll(list);
            }
        }


        modelMap.addAttribute("anchorUserList", anchorUserList);
        modelMap.addAttribute("model", model);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("modelList", modelList);
        modelMap.addAttribute("roleList", roleList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("nodeModelList", nodeModelList);
        modelMap.addAttribute("infoModelList", infoModelList);
        modelMap.addAttribute("infoModel", bean.getInfoModel());
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("showDescendants", showDescendants);
        modelMap.addAttribute(OPRT, EDIT);
        modelMap.addAttribute("returnUrl", returnUrl);
        return "core/publish_center/node_form";
    }

    /**
     * 保存栏目
     * @param cid
     * @param bean 主数据对象
     * @param detail 详情对象
     * @param nodeAnchorIds 关联主播
     * @param infoPermIds 文档权限
     * @param nodePermIds 栏目权限
     * @param viewGroupIds 浏览权限
     * @param contriGroupIds 投稿权限
     * @param commentGroupIds 评论权限
     * @param viewOrgIds
     * @param parentId   父栏目id
     * @param nodeModelId 栏目模型
     * @param infoModelId 新闻模型
     * @param workflowId
     * @param anchourUserId 主播用户
     * @param infoPermIdsExist
     * @param nodePermIdsExist
     * @param viewGroupIdsExist
     * @param contriGroupIdsExist
     * @param commentGroupIdsExist
     * @param queryParentId 父栏目id
     * @param returnUrl 返回url
     * @param showDescendants 显示子栏目
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:node:savein")
    @RequestMapping("nodesave.do")
    public String nodesave(Integer cid, Node bean, NodeDetail detail,Integer[] nodeAnchorIds, Integer[] infoPermIds, Integer[] nodePermIds,
                       Integer[] viewGroupIds, Integer[] contriGroupIds, Integer[] commentGroupIds, Integer[] viewOrgIds,
                       Integer parentId, Integer nodeModelId, Integer infoModelId, Integer workflowId,Integer anchourUserId,
                       @RequestParam(defaultValue = "false") boolean infoPermIdsExist,
                       @RequestParam(defaultValue = "false") boolean nodePermIdsExist,
                       @RequestParam(defaultValue = "false") boolean viewGroupIdsExist,
                       @RequestParam(defaultValue = "false") boolean contriGroupIdsExist,
                       @RequestParam(defaultValue = "false") boolean commentGroupIdsExist, Integer queryParentId,String returnUrl,
                       Boolean showDescendants, String redirect, HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        if (parentId != null) {
            Node parent = nodeQuery.get(parentId);
            Backends.validateDataInSite(parent, siteId);
        }
        if (!infoPermIdsExist) {
            infoPermIds = getInfoPermIds(siteId, parentId);
        }
        if (!nodePermIdsExist) {
            nodePermIds = getNodePermIds(siteId, parentId);
        }
        if (!viewGroupIdsExist) {
            viewGroupIds = getViewGroupIds(siteId, parentId);
        }
        if (!contriGroupIdsExist) {
            contriGroupIds = getContriGroupIds(siteId, parentId);
        }
        if (!commentGroupIdsExist) {
            commentGroupIds = getCommentGroupIds(siteId, parentId);
        }
        //主播动态 关联主播用户
        if(anchourUserId!=null){
            bean.setAnchorUser(userService.get(anchourUserId));
        }
        //配置模版生成参数
        Model m=modelService.get(nodeModelId);
        if(Constants.MODEL_FLAG_CITY_DETAIL.equals(m.getFlag())){
            //市州详情
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(m.getFlag())){
            //主播栏目详情
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(m.getFlag())){
            //主播圈动态
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(false);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_NEWS.equals(m.getFlag()) || Constants.MODEL_FLAG_ACTIVITY_NODE.equals(m.getFlag())){
            //普通新闻
            detail.setNodePath("/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }

        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        service.save(bean, detail, nodeAnchorIds,customs, clobs, infoPermIds, nodePermIds, viewGroupIds, contriGroupIds,
                commentGroupIds, viewOrgIds, parentId, nodeModelId, infoModelId, workflowId, userId, siteId);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("栏目管理.新增栏目", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
        logger.info("栏目管理.新增栏目,name={}.", bean.getName());
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("showDescendants", showDescendants);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addFlashAttribute("refreshLeft", true);
        ra.addAttribute("returnUrl",returnUrl);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:"+returnUrl+".do";
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            ra.addAttribute("parentId", parentId);
            return "redirect:nodecreate.do";
        } else {
            ra.addAttribute("id", bean.getId());
            return "redirect:nodeedit.do";
        }
    }

    /**
     * 修改栏目
     * @param bean 栏目主数据对象
     * @param detail 栏目详情对象
     * @param nodeAnchorIds 关联主播
     * @param infoPermIds 文档权限
     * @param nodePermIds 栏目权限
     * @param viewGroupIds 浏览权限
     * @param contriGroupIds 投稿权限
     * @param commentGroupIds 评论权限
     * @param viewOrgIds
     * @param parentId 父栏目
     * @param nodeModelId 栏目模型
     * @param anchourUserId 主播用户
     * @param infoModelId 文档模型
     * @param workflowId
     * @param infoPermIdsExist
     * @param nodePermIdsExist
     * @param viewGroupIdsExist
     * @param contriGroupIdsExist
     * @param commentGroupIdsExist
     * @param position
     * @param queryParentId
     * @param returnUrl 返回url
     * @param showDescendants
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:node:update")
    @RequestMapping("nodeupdate.do")
    public String nodeupdate(@ModelAttribute("nodebean") Node bean, @ModelAttribute("nodedetail") NodeDetail detail,Integer[] nodeAnchorIds,
                         Integer[] infoPermIds, Integer[] nodePermIds, Integer[] viewGroupIds, Integer[] contriGroupIds,
                         Integer[] commentGroupIds, Integer[] viewOrgIds, Integer parentId, Integer nodeModelId,Integer anchourUserId,
                         Integer infoModelId, Integer workflowId, @RequestParam(defaultValue = "false") boolean infoPermIdsExist,
                         @RequestParam(defaultValue = "false") boolean nodePermIdsExist,
                         @RequestParam(defaultValue = "false") boolean viewGroupIdsExist,
                         @RequestParam(defaultValue = "false") boolean contriGroupIdsExist,
                         @RequestParam(defaultValue = "false") boolean commentGroupIdsExist, Integer position,
                         Integer queryParentId,String returnUrl,Boolean showDescendants, String redirect, HttpServletRequest request,
                         RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        if (parentId != null) {
            Node parent = nodeQuery.get(parentId);
            Backends.validateDataInSite(parent, site.getId());
        }
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        if (infoPermIdsExist && infoPermIds == null) {
            infoPermIds = new Integer[0];
        }
        if (nodePermIdsExist && nodePermIds == null) {
            nodePermIds = new Integer[0];
        }
        if (viewGroupIdsExist && viewGroupIds == null) {
            viewGroupIds = new Integer[0];
        }
        if (contriGroupIdsExist && contriGroupIds == null) {
            contriGroupIds = new Integer[0];
        }
        if (commentGroupIdsExist && commentGroupIds == null) {
            commentGroupIds = new Integer[0];
        }
        if (viewOrgIds == null) {
            viewOrgIds = new Integer[0];
        }
        if (nodeAnchorIds == null) {
            nodeAnchorIds=new Integer[0];
        }
        //主播动态 关联主播用户
        if(anchourUserId!=null){
           bean.setAnchorUser(userService.get(anchourUserId));
        }else{
            bean.setAnchorUser(null);
        }

        //配置模版生成参数
        if(Constants.MODEL_FLAG_CITY_DETAIL.equals(bean.getNodeModel().getFlag())){
            //市州详情
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_ANCHOR_NODE_DETAIL.equals(bean.getNodeModel().getFlag())){
            //主播栏目详情
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(bean.getNodeModel().getFlag())){
            //主播圈动态
            detail.setNodePath("/{node_parent_number}/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(false);
            detail.setInfoPath("/{node_parent_number}/{node_number}/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }else if(Constants.MODEL_FLAG_NEWS.equals(bean.getNodeModel().getFlag()) || Constants.MODEL_FLAG_ACTIVITY_NODE.equals(bean.getNodeModel().getFlag())){
            //普通新闻
            detail.setNodePath("/{node_number}/{node_number}");
            detail.setGenerateNode(true);
            detail.setNodeExtension(".json");
            detail.setDefPage(false);

            detail.setGenerateInfo(true);
            detail.setInfoPath("/{node_number}/{info_id}");
            detail.setInfoExtension(".json");
            detail.setStaticMethod(Node.STATIC_INFO);

            detail.setStaticPage(20);
        }

        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        service.update(bean, detail,nodeAnchorIds, customs, clobs, infoPermIds, nodePermIds, viewGroupIds, contriGroupIds,
                commentGroupIds, viewOrgIds, nodeModelId, infoModelId, workflowId);
        Integer userId = Context.getCurrentUserId();
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("栏目管理.修改栏目", bean.getTitle(), null, bean.getId(), ip, userId, site.getId());
        logger.info("栏目管理.修改栏目,name={}.", bean.getName());
        // 移动节点
        if (parentId != null && bean.getParent() != null && !parentId.equals(bean.getParent().getId())) {
            service.move(new Integer[] { bean.getId() }, parentId, site.getId());
        }
        logger.info("update Node, name={}.", bean.getName());
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("showDescendants", showDescendants);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addFlashAttribute("refreshLeft", true);
        ra.addAttribute("returnUrl", returnUrl);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:"+returnUrl+".do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:nodeedit.do";
        }
    }

    /**
     * 栏目批量更改
     * @param id 栏目id
     * @param name 名称
     * @param number 编码
     * @param views 浏览数
     * @param hidden 隐藏
     * @param publish 是否发布
     * @param queryParentId 父栏目
     * @param showDescendants
     * @param pageable 分页对象
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:pub_center:batch_update")
    @RequestMapping("nodebatch_update.do")
    public String nodebatchUpdate(Integer[] id, String[] name, String[] number, Integer[] views, Boolean[] hidden,String[] publish,
                              Integer queryParentId, Boolean showDescendants, Pageable pageable, HttpServletRequest request,
                              RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        validateIds(id, siteId);
        if (ArrayUtils.isNotEmpty(id)) {
            // 有排序的情况下不更新树结构，以免引误操作。
            boolean isUpdateTree = pageable.getSort() == null;
            Node[] beans = service.batchUpdate(id, name, number, views, hidden, siteId,publish,isUpdateTree);
            Integer userId = Context.getCurrentUserId();
            String ip = Servlets.getRemoteAddr(request);
            for (Node bean : beans) {
                logService.operation("栏目管理.批量修改栏目", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("栏目管理.批量修改栏目, name={}.", bean.getName());
            }
        }
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("showDescendants", showDescendants);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addFlashAttribute("refreshLeft", true);
        return "redirect:nodelist.do";
    }

    /**
     * 栏目删除
     * @param ids 栏目id
     * @param queryParentId 父栏目id
     * @param returnUrl 返回url
     * @param showDescendants 显示子栏目
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:publish_center:delete")
    @RequestMapping("nodedelete.do")
    public String nodedelete(Integer[] ids, Integer queryParentId,String returnUrl, Boolean showDescendants, HttpServletRequest request,
                         RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        for (Integer id : ids) {
            Node bean = nodeQuery.get(id);
            Backends.validateDataInSite(bean, site.getId());
            if (!bean.isDataPerm(user)) {
                throw new CmsException("accessDenied");
            }
        }
        Node[] beans = service.delete(ids);
        String ip = Servlets.getRemoteAddr(request);
        for (Node bean : beans) {
            logService
                    .operation("栏目管理.删除栏目", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("栏目管理.删除栏目, name={}.", bean.getName());
        }
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("showDescendants", showDescendants);
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        ra.addFlashAttribute("refreshLeft", true);
        return "redirect:"+returnUrl+".do";
    }

//    @RequiresPermissions("core:node:move_form")
    @RequestMapping("nodemove_form.do")
    public String nodemoveForm(Integer[] ids, Boolean noChecked, Integer queryParentId, Boolean showDescendants,
                           HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        List<Node> selectedList = nodeQuery.findByIds(ids);
        // 获得已选择节点的所有父节点ID，用于展开树。
        Set<Integer> selectedPids = new HashSet<Integer>();
        // 获得选中节点的ID
        Set<Integer> selectedIds = new HashSet<Integer>();
        for (Node node : selectedList) {
            selectedIds.add(node.getId());
            Node parent = node.getParent();
            while (parent != null) {
                selectedPids.add(parent.getId());
                parent = parent.getParent();
            }
        }
        List<Node> list = nodeQuery.findList(site.getId(), null);
        modelMap.addAttribute("nodePerms", user.getNodePerms(site.getId()));
        modelMap.addAttribute("list", list);
        modelMap.addAttribute("noChecked", noChecked);
        modelMap.addAttribute("selectedList", selectedList);
        modelMap.addAttribute("selectedIds", selectedIds.toArray());
        modelMap.addAttribute("selectedPids", selectedPids.toArray());
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("showDescendants", showDescendants);
        return "core/publish_center/node_move";
    }

//    @RequiresPermissions("core:node:move_submit")
    @RequestMapping("nodemove_submit.do")
    public String nodemoveSubmit(Integer[] ids, Integer id, Integer queryParentId, Boolean showDescendants,
                             HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        validateIds(ids, site.getId());
        service.move(ids, id, site.getId());
        Integer userId = Context.getCurrentUserId();
        String ip = Servlets.getRemoteAddr(request);
        Node bean;
        for (Integer bid : ids) {
            bean = nodeQuery.get(bid);
            logService.operation("栏目管理.移动栏目", bean.getTitle(), null, bean.getId(), ip, userId, site.getId());
            logger.info("栏目管理.移动栏目, name={}.", bean.getName());
        }
        // bug??
        // ra.addAttribute("ids", ids);
        ra.addAttribute("noChecked", true);
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("showDescendants", showDescendants);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addFlashAttribute("refreshLeft", true);
        return "redirect:nodemove_form.do?ids=" + StringUtils.join(ids, "&ids=");
    }

    /**
     * 主播查询
     * @param queryParentId 父id
     * @param showDescendants 显示子栏目
     * @param pageable 分页对象
     * @param request
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:dynamic:list")
    @RequestMapping("dynamiclist.do")
    public String dynamiclist(Integer queryParentId,@RequestParam(defaultValue = "true") boolean showDescendants,
                             @PageableDefault(sort = { "treeNumber", "id" }, direction = Sort.Direction.ASC) Pageable pageable,
                             HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Node parent = null;
        if (queryParentId != null) {
            parent = nodeQuery.get(queryParentId);
        }
        if (parent == null) {
            parent = nodeQuery.findRoot(siteId);
            if (parent != null) {
                queryParentId = parent.getId();
            }
        }
        String treeNumber = null;
        if (showDescendants && parent != null) {
            treeNumber = parent.getTreeNumber();
        }
        String name=request.getParameter("search_CONTAIN_name");
        String anchorCity=request.getParameter("search_EQ_city");
        Integer[] sites=new Integer[]{siteId};
        Page<Node>  pagedList= nodeQuery.findPage(sites, queryParentId,treeNumber,true,false, null,
                null,null,null,null,null,null,
                pageable,name,anchorCity);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("pagedList", pagedList);
        return "core/publish_center/dynamic_node_list";
    }

    /**
     * 主播动态查询
     * @param queryParentId 父栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param pageable 分页对象
     * @param request
     * @param modelMap
     * @return 结果页面
     */

//    @RequiresPermissions("core:dynamiclnfo:list")
    @RequestMapping("dynamiclnfolist.do")
    public String dynamiclnfolist(Integer queryParentId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                                  @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                                  HttpServletRequest request, org.springframework.ui.Model modelMap) {
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryParentId != null) {
            queryNode = nodeQuery.get(queryParentId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryParentId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryParentId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
        params.put("EQ_newsType",new String[]{"10"});   //主播动态
        Page<Info> pagedList = infoQuery.findAll(null,siteId, mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, pageable,null);
        List<Attribute> attributeList = attributeService.findList(siteId);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        return "core/publish_center/dynamic_info_list";
    }


    /**
     * 新闻逻辑删除
     * @param method 跳转方法
     * @param nodeFlag 栏目标记
     * @param returnUrl 返回url
     * @param ids id集合
     * @param queryNodeId 栏目id
     * @param queryNodeType 栏目类型
     * @param queryInfoPermType 权限
     * @param queryStatus 状态
     * @param request 请求
     * @param ra 重定向
     * @return 结果页面方法
     */
    @RequiresPermissions(value = {
            "core:pub_center:logic_delete",
            "core:pub_center:logic_deletes",
            "core:pub_center:logic_delete01"
    },logical =Logical.OR )
    @RequestMapping("infologic_delete.do")
    public String infologicDelete(String method,String nodeFlag,String returnUrl,Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                              String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        if(method==null){
            if (returnUrl == null) {
                method="infolist";
            }else{
                method=returnUrl;
                //硬编码处理
                if("info_activity_list".equals(returnUrl)){
                    method="infolist";
                }
            }
        }
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            Info bean = infoQuery.get(id);
            if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
                throw new CmsException("accessDenied");
            }
        }
        String ip = Servlets.getRemoteAddr(request);
        List<Info> beans = infoService.logicDelete(ids);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostLogicDelete");
//        }
        for (Info bean : beans) {
            logService.operation("栏目管理.新闻逻辑删除", bean.getTitle(), null, bean.getId(), ip, user.getId(),
                    site.getId());
            logger.info("栏目管理.新闻逻辑删除, name={}.", bean.getTitle());
        }
        ra.addAttribute("queryParentId", queryNodeId);
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("returnUrl", returnUrl);
        ra.addAttribute("nodeFlag", nodeFlag);
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:"+method+".do";
    }

    /**
     * 市州查询
     * @param queryParentId 父id
     * @param showDescendants 显示子栏目
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap 视图对象
     * @return 结果页面
     */
//    @RequiresPermissions("core:citynode:list")
    @RequestMapping("citynodelist.do")
    public String citynodelist(Integer queryParentId,@RequestParam(defaultValue = "true") boolean showDescendants,
                             @PageableDefault(sort = { "treeNumber", "id" }, direction = Sort.Direction.ASC) Pageable pageable,
                             HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Node parent = null;
        if (queryParentId != null) {
            parent = nodeQuery.get(queryParentId);
        }
        if (parent == null) {
            parent = nodeQuery.findRoot(siteId);
            if (parent != null) {
                queryParentId = parent.getId();
            }
        }
        String treeNumber = null;
        if (showDescendants && parent != null) {
            treeNumber = parent.getTreeNumber();
        }
        String name=request.getParameter("search_CONTAIN_name");
        Integer[] sites=new Integer[]{siteId};
        Page<Node>  pagedList= nodeQuery.findPage(sites, queryParentId,treeNumber,true,false, null,
                null,null,null,null,null,null,
                pageable,name,null);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("parent", parent);
        modelMap.addAttribute("pagedList", pagedList);
        return "core/publish_center/city_node_list";
    }

    /**
     * 新闻查询
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param returnUrl 返回url
     * @param targetNodeId 目标id
     * @param orderId 顺序
     * @param nodeFlag 标记
     * @param directoryId 爬虫文库
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions(value={
            "core:pub_center:infolistClums","core:site:forward",
            "core:pub_center:infolist",
            "core:pub_center:audit", "core:pub_center:back", "core:pub_center:auditz", "core:pub_center:released", "core:pub_center:published", "core:pub_center:expired", "core:pub_center:draft", "core:pub_center:rejection", "core:pub_center:contribute", "core:pub_center:collect", "core:pub_center:recycle",
            "core:pub_center:infolists",
            "core:pub_center:audits", "core:pub_center:backs", "core:pub_center:auditzs", "core:pub_center:releaseds", "core:pub_center:publisheds", "core:pub_center:expireds", "core:pub_center:drafts", "core:pub_center:rejections", "core:pub_center:contributes", "core:pub_center:collects", "core:pub_center:recycles",
            "core:pub_center:audit01", "core:pub_center:back01", "core:pub_center:auditz01", "core:pub_center:released01", "core:pub_center:published01", "core:pub_center:expired01", "core:pub_center:draft01", "core:pub_center:rejection01", "core:pub_center:contribute01", "core:pub_center:collect01", "core:pub_center:recycle01",
    },logical = Logical.OR)
    @RequestMapping("infolist.do")
    public String infolist(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                           String returnUrl,Integer targetNodeId,Integer orderId,String nodeFlag,String directoryId,
                           @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                           HttpServletRequest request, org.springframework.ui.Model modelMap) {
        String url="core/publish_center/info_list";
        if(returnUrl!=null){
            url="core/publish_center/"+returnUrl;
        }
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        Site site=Context.getCurrentSite();
        User user = Context.getCurrentUser();

        Map returnMap = getFlagByNodeIds(CRAWLER_LIBRARY, siteId);

        Object nodes =null;

        if (returnMap != null){
            nodes=returnMap.get("nodes");
        }

        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        if(Constants.CRAWLER_LIBRARY.equals(nodeFlag)) {
            if(returnUrl==null){
                url="core/publish_center/crawler_info_list";
            }
            nodeId=null;
        }else if(Constants.MODEL_FLAG_DRAFTS_NODE.equals(nodeFlag)){
            url="core/publish_center/crawler_info_list01";
            nodeId=null;
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }


//        Sort defSort = new Sort(Sort.Direction.DESC, "priority");
//        Limitable limitable = new LimitRequest(null,null, defSort);
//
//        List<Info> list = infoFulltextService.list(new Integer[]{siteId}, null, null, null,
//                null,new String[]{"A"}, null,null, "最高奖", null, null,
//                null, null, null, null, limitable, null);

        Integer[] nodeIds=null;
        if(Constants.CRAWLER_LIBRARY.equals(nodeFlag)) {
            if (directoryId != null && directoryId != ""){
                nodeIds = new Integer[]{Integer.valueOf(directoryId)};
            }else{
                if(returnMap!=null){
                    nodeIds = (Integer[])returnMap.get("nodeIds");
                }
            }
        }
        if(Constants.MODEL_FLAG_DRAFTS_NODE.equals(nodeFlag)){
             nodeIds=getNodeIdsByFlag(nodeFlag,siteId);
        }
        params.put("NOTEQ_newsType",new String[]{"10"});   //主播动态
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
        Page<Info> pagedList = infoQuery.findAll(null,siteId, mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, pageable,nodeIds);
        List<Attribute> attributeList = attributeService.findList(siteId);

        if(queryNode!=null && queryNode.getNodeModel().getFlag().equals(Constants.MODEL_FLAG_ACTIVITY_NODE)){
            url="core/publish_center/info_activity_list";
        }
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node",queryNode);
        modelMap.addAttribute("returnUrl",returnUrl);
        modelMap.addAttribute("targetNodeId",targetNodeId);
        modelMap.addAttribute("orderId",orderId);
        modelMap.addAttribute("nodes",nodes);
        modelMap.addAttribute("nodeFlag",nodeFlag);
        modelMap.addAttribute("directoryId",directoryId);
        //是否可以发布到直播盐都站点市州圈 0是 1否
        int isPubCity=1;
        if(site.getPublishNodeid()!=null && site.getPublishNodeid().intValue()>0){
            isPubCity=0;
        }
        modelMap.addAttribute("isPubCity",isPubCity);
        return url;
    }

    /**
     * 跳转到新闻创建页面
     * @param id 新闻id
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param refInfoId 引用新闻id
     * @param returnUrl 返回url
     * @param directoryId 爬虫文库
     * @param nodeFlag 栏目标记
     * @param queryStatus 状态
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:info:create")
    @RequestMapping("infocreate.do")
    public String infocreate(Integer id, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                         Integer refInfoId,String returnUrl,Integer directoryId,String nodeFlag,
                         String queryStatus, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        if(returnUrl==null){
            returnUrl="core/publish_center/info_form";
        }
	    Site site = Context.getCurrentSite();
        if (id != null) {
            Info bean = infoQuery.get(id);
            Backends.validateDataInSite(bean, site.getId());
            modelMap.addAttribute("bean", bean);
        }
        Node node;
        if (queryNodeId == null) {
            node = nodeQuery.findRoot(site.getId());
            if (node == null) {
                throw new CmsException("info.error.nodeNotFound");
            }
        } else {
            node = nodeQuery.get(queryNodeId);
        }
        if(refInfoId!=null){
            Info refInfo=infoQuery.get(refInfoId);
            modelMap.addAttribute("refInfo", refInfo);
        }
        Backends.validateDataInSite(node, site.getId());
        Model model = node.getInfoModel();
        List<Attribute> attrList = attributeService.findList(site.getId());
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();
        //查询主播数据
        String anchorStr=getAnchorsJosnStr(site);
        //查询市州地区数据
        String cityNodeStr=getCityNodesJosnStr(site);
        modelMap.addAttribute("cityNodeStr",cityNodeStr);
        modelMap.addAttribute("anchorStr",anchorStr);
        modelMap.addAttribute("model", model);
        modelMap.addAttribute("node", node);
        modelMap.addAttribute("attrList", attrList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("directoryId",directoryId);
        modelMap.addAttribute("nodeFlag",nodeFlag);
        modelMap.addAttribute(OPRT, CREATE);
        return returnUrl;
    }

    /**
     * 跳转到新闻修改页面
     * @param id 新闻id
     * @param position
     * @param queryNodeId 栏目id
     * @param returnUrl 返回url
     * @param queryParentId 父栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:info:edit")
    @RequestMapping("infoedit.do")
    public String infoedit(Integer id, Integer position, Integer queryNodeId,String returnUrl,Integer queryParentId,
                       @RequestParam(defaultValue = "0") int queryNodeType, Integer queryInfoPermType, String queryStatus,
                       @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        if(returnUrl==null){
            returnUrl="core/publish_center/info_form";
        }
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Info bean = infoQuery.get(id);
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Integer infoPermType = user.getInfoPermType(site.getId());
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(site.getId());
        RowSide<Info> side = infoQuery.findSide(site.getId(), mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, bean, position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);

        Node node = bean.getNode();
        Model model = bean.getModel();
        List<Attribute> attrList = attributeService.findList(site.getId());
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();

        //查询主播数据
        String anchorStr=getAnchorsJosnStr(site);
        modelMap.addAttribute("anchorStr",anchorStr);
        //获取新闻所属主播
        if(bean!=null){
          List<Node> selectAnchors=bean.getNodesExcludeMain();
          String selectAnchorStr="";
          StringBuffer buffer=new StringBuffer("");
          if(selectAnchors!=null && selectAnchors.size()>0) {
              for (Node anchor : selectAnchors) {
                  buffer.append(anchor.getId()).append(",");
              }
          }
          selectAnchorStr=buffer.toString();
          if(StringUtils.isNotBlank(selectAnchorStr)){
              selectAnchorStr=selectAnchorStr.substring(0, selectAnchorStr.length() - 1);
          }
          modelMap.addAttribute("selectAnchorStr",selectAnchorStr);
            List<Special> specials=bean.getSpecials();
            StringBuffer speTitle=new StringBuffer("");
            if(specials!=null && specials.size()>0) {
                for (Special spe : specials) {
                    speTitle.append(spe.getTitle()).append(",");
                }
                modelMap.addAttribute("specialIdsNameDisplay", speTitle.substring(0,speTitle.length()-1));
            }else{
                modelMap.addAttribute("specialIdsNameDisplay", speTitle.toString());
            }
        }
        //查询市州地区数据
        String cityNodeStr=getCityNodesJosnStr(site);
        modelMap.addAttribute("cityNodeStr",cityNodeStr);
        //查询发布到市州栏目数据
        modelMap.addAttribute("selectCityNodeStr",bean.getCityNodes());

        modelMap.addAttribute("model", model);
        modelMap.addAttribute("node", node);
        modelMap.addAttribute("attrList", attrList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute(OPRT, EDIT);
        modelMap.addAttribute("queryParentId",queryParentId);
        return returnUrl;
    }

    /**
     * 新闻保存
     * @param bean 新闻主数据对象
     * @param detail 新闻详情对象
     * @param nodeIds 栏目id
     * @param specialIds 专题
     * @param viewGroupIds 浏览权限
     * @param viewOrgIds
     * @param attrIds 属性
     * @param nodeId 栏目
     * @param tagKeywords 关键词
     * @param voteIds 投票
     * @param draft 草稿
     * @param imagesName 图片名称
     * @param imagesText 图片文本
     * @param imagesImage 图片集
     * @param filesName 文件名称
     * @param filesFile 文件集
     * @param filesLength 文件大小
     * @param redirect
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param refInfoId 引用新闻id
     * @param crawler 爬虫
     * @param request
     * @param ra
     * @return
     */
//    @RequiresPermissions("core:info:save")
    @RequestMapping("infosave.do")
    public String infosave(Info bean, InfoDetail detail, Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds,
                       Integer[] viewOrgIds, Integer[] attrIds, Integer nodeId, String tagKeywords,Integer[] voteIds,
                       @RequestParam(defaultValue = "false") boolean draft, String[] imagesName, String[] imagesText,
                       String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, String redirect,
                       Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                       Integer refInfoId,Integer crawler,String cityNodes,
                       HttpServletRequest request, RedirectAttributes ra) {

        String paramTitle=detail.getTitle();
        if(paramTitle!=null){
            paramTitle=paramTitle.replaceAll("\"(.*?)\"","“$1”").replaceAll("'(.*?)'","‘$1’");
            detail.setTitle(paramTitle);
        }

        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesText[i])
                        || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        //引用文章
        if(refInfoId!=null){
            Info refInfo=infoQuery.get(refInfoId);
            bean.setRefInfo(refInfo);
        }
        String status = draft ? Info.DRAFT : null;
        if(crawler!=null && crawler.intValue()==1){
            redirect="list";
           /* if(draft){  //发布到时讯
                status="A";
                bean.setStatus("A");
                Integer[] targetIds=getNodeIdsByFlag(Constants.MODEL_FLAG_CURRENTNEWS,siteId);
                if(targetIds!=null && targetIds.length>0){
                    nodeId=targetIds[0];
                }
                ra.addAttribute("queryStatus", queryStatus);
            }else{  //保存到草稿箱栏目
//                status="F";
               Integer[] targetIds=getNodeIdsByFlag(Constants.MODEL_FLAG_DRAFTS_NODE,siteId);
               if(targetIds!=null && targetIds.length>0){
                   nodeId=targetIds[0];
               }
            }*/
            ra.addAttribute("returnUrl","crawler_info_list");
        }
        if(specialIds!=null && specialIds.length==1){
            if(specialIds[0]==null){
                specialIds=null;
            }
        }
        if(voteIds!=null && voteIds.length==1){
            if(voteIds[0]==null){
                voteIds=null;
            }
        }

        if(StringUtils.isNotBlank(cityNodes)){
            bean.setCityNodes(cityNodes);
        }

        Info result=infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,voteIds, customs, clobs, images, files,
                attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
//        infoService.updateHtmlThread(result.getId(),false,"firePostSave");
        //发布到多个市州栏目
        infoService.saveInfoToCityNode(cityNodes,result);
        String ip = Servlets.getRemoteAddr(request);
        if(refInfoId!=null && bean.getRefInfo()!=null){
            logService.operation("栏目管理.新闻新增", "引用的新闻id："+bean.getId()+","+bean.getTitle(),"cityNodes:"+cityNodes, bean.getId(), ip, userId, siteId);
        }else {
            logService.operation("栏目管理.新闻新增", bean.getTitle(), "cityNodes:"+cityNodes, bean.getId(), ip, userId, siteId);
        }
        logger.info("栏目管理.新闻新增, title={},refInfoId={}", bean.getTitle(),refInfoId);
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:infolist.do";
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            return "redirect:infocreate.do";
        } else {
            ra.addAttribute("id", bean.getId());
            return "redirect:infoedit.do";
        }
    }

    /**
     * 新闻修改
     * @param bean 新闻主数据对象
     * @param detail 新闻详情对象
     * @param nodeIds 栏目id
     * @param specialIds 专题
     * @param viewGroupIds 浏览权限
     * @param viewOrgIds
     * @param attrIds 属性
     * @param nodeId 栏目
     * @param tagKeywords 关键词
     * @param pass 通过
     * @param voteIds 投票
     * @param remainDescription
     * @param imagesName 图片名称
     * @param imagesText 图片文本
     * @param imagesImage 图片集
     * @param filesName 文件名称
     * @param filesFile 文件集
     * @param filesLength 文件大小
     * @param position
     * @param nodeFlag 栏目标记
     * @param queryNodeId 栏目id
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus 状态
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:info:update")
    @RequestMapping("infoupdate.do")
    public String infoupdate(@ModelAttribute("bean") Info bean, @ModelAttribute("detail") InfoDetail detail,
                         Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds, Integer[] viewOrgIds, Integer[] attrIds,
                         Integer nodeId, String tagKeywords, @RequestParam(defaultValue = "false") boolean pass,Integer[] voteIds,
                         @RequestParam(defaultValue = "false") boolean remainDescription, String[] imagesName, String[] imagesText,
                         String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, Integer position,String nodeFlag,
                         Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,String cityNodes,
                         HttpServletRequest request, RedirectAttributes ra) {

        String paramTitle=detail.getTitle();
        if(paramTitle!=null){
            paramTitle=paramTitle.replaceAll("\"(.*?)\"","“$1”").replaceAll("'(.*?)'","‘$1’");
            detail.setTitle(paramTitle);
        }
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (!remainDescription || StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        if(specialIds!=null && specialIds.length==1){
           if(specialIds[0]==null){
               specialIds=null;
           }
        }
        if(voteIds!=null && voteIds.length==1){
            if(voteIds[0]==null){
                voteIds=null;
            }
        }
        if (specialIds == null) {
            specialIds = new Integer[0];
        }
        if (viewGroupIds == null) {
            viewGroupIds = new Integer[0];
        }
        if (viewOrgIds == null) {
            viewOrgIds = new Integer[0];
        }
        if (attrIds == null) {
            attrIds = new Integer[0];
        }
        if (tagNames == null) {
            tagNames = new String[0];
        }
        if (voteIds == null) {
            voteIds = new Integer[0];
        }
        bean.setCityNodes(cityNodes);
        infoService.update(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,voteIds, customs, clobs, images, files,
                attrIds, attrImages, tagNames, nodeId, user, pass, false);
//        infoService.updateHtmlThread(bean.getId(),false,"firePostUpdate");
        infoService.saveInfoToCityNode(cityNodes,bean);
        String ip = Servlets.getRemoteAddr(request);
        logService.operation("栏目管理.新闻修改", bean.getTitle(), "cityNodes:"+cityNodes, bean.getId(), ip, user.getId(), site.getId());
        logger.info("栏目管理.新闻修改, title={}.", bean.getTitle());
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("nodeFlag", nodeFlag);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:infolist.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:infoedit.do";
        }
    }

    /**
     * 新闻删除
     * @param ids 新闻id集合
     * @param returnUrl 返回url
     * @param nodeFlag 栏目标记
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param request
     * @param ra 结果页面
     * @return
     */
    @RequiresPermissions(value = {
            "core:pub_center:infodelete",
            "core:pub_center:infodeletes",
            "core:info:delete01"
    },logical = Logical.OR)
    @RequestMapping("infodelete.do")
    public String infodelete(Integer[] ids,String returnUrl,String nodeFlag,Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                         String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            Info bean = infoQuery.get(id);
            if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
                throw new CmsException("accessDenied");
            }
        }
        List<Info> beans = infoService.delete(ids);
//        infoService.batchupdateHtmlThread(Arrays.asList(ids),true,"firePostDelete");
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService
                    .operation("栏目管理.新闻物理删除", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("栏目管理.新闻物理删除, name={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("returnUrl", returnUrl);
        ra.addAttribute("nodeFlag", nodeFlag);
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:infolist.do";
    }

    /**
     * 撤销删除
     * @param ids 新闻集合id
     * @param returnUrl 返回url
     * @param nodeFlag 栏目标记
     * @param queryNodeId 栏目
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:pub_center:inforecall",
            "core:pub_center:inforecalls",
    },logical = Logical.OR)
    @RequestMapping("inforecall.do")
    public String inforecall(Integer[] ids,String returnUrl,String nodeFlag, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                         String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            Info bean = infoQuery.get(id);
            if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
                throw new CmsException("accessDenied");
            }
        }
        List<Info> beans = infoService.recall(ids);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostLogicDelete");
//        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService
                    .operation("栏目管理.新闻撤销删除", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("栏目管理.新闻撤销删除, name={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("returnUrl", returnUrl);
        ra.addAttribute("nodeFlag", nodeFlag);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        return "redirect:infolist.do";
    }

    /**
     * 审核通过
     * @param ids 新闻id集合
     * @param opinion
     * @param returnUrl 返回url
     * @param nodeFlag 栏目标记
     * @param position
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param redirect
     * @param pubCityNode 市州发文使用
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:pub_center:infoaudit_pass",
            "core:pub_center:infoaudit_pass01",
            "core:pub_center:infoaudit_passs",
    },logical = Logical.OR)
    @RequestMapping("infoaudit_pass.do")
    public String infoauditPass(Integer[] ids, String opinion,String returnUrl,String nodeFlag, Integer position, Integer queryNodeId,
                            Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,Integer pubCityNode,
                            HttpServletRequest request, RedirectAttributes ra) {
	    String msg=OPERATION_SUCCESS;
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.pass(ids, userId, opinion);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostPass");
//        }
        //发布到市州圈
        if(pubCityNode!=null && pubCityNode.intValue()==0){
            Site site=Context.getCurrentSite();
            if(site.getPublishNodeid()!=null && site.getPublishNodeid().intValue()>0){
                infoService.pubCityInfo(beans,site.getPublishNodeid(),userId);
                Node cityNode=nodeQuery.get(site.getPublishNodeid());
//                htmlGenerator.makeInfo(cityNode.getSite().getId(), cityNode.getId(),cityNode.getName(),true,userId);
                htmlGenerator.makeNode(cityNode.getSite().getId(), cityNode.getId(),cityNode.getName(), true, userId,null);
            }else{
                msg=PUB_CITY_FAILURE;
            }
        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.新闻发布", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("栏目管理.新闻发布, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, msg);
        if (Constants.REDIRECT_EDIT.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoedit.do";
        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoview.do";
        } else {
            ra.addAttribute("returnUrl", returnUrl);
            ra.addAttribute("nodeFlag", nodeFlag);
            return "redirect:infolist.do";
        }
    }

    /**
     * 撤销审核
     * @param ids 新闻id集合
     * @param returnUrl 返回url
     * @param nodeFlag 栏目标记
     * @param opinion
     * @param position
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param redirect
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:pub_center:infoaudit_reject",
            "core:pub_center:infoaudit_reject01",
            "core:pub_center:infoaudit_rejects",
    },logical = Logical.OR)
    @RequestMapping("infoaudit_reject.do")
    public String infoauditReject(Integer[] ids,String returnUrl,String nodeFlag, String opinion, Integer position, Integer queryNodeId,
                              Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                              HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.reject(ids, userId, opinion, false);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostReject");
//        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.新闻撤销审核", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("栏目管理.新闻撤销审核, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        if (Constants.REDIRECT_EDIT.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoedit.do";
        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoview.do";
        } else {
            ra.addAttribute("nodeFlag", nodeFlag);
            ra.addAttribute("returnUrl", returnUrl);
            return "redirect:infolist.do";
        }
    }

    /**
     * 退稿
     * @param ids 新闻id集合
     * @param nodeFlag 栏目标记
     * @param returnUrl 返回url
     * @param opinion
     * @param position
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param redirect
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions(value = {
            "core:pub_center:infoaudit_return",
            "core:pub_center:infoaudit_return01",
            "core:pub_center:infoaudit_returns",
    },logical = Logical.OR)
    @RequestMapping("infoaudit_return.do")
    public String infoauditReturn(Integer[] ids,String nodeFlag,String returnUrl, String opinion, Integer position, Integer queryNodeId,
                              Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                              HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.reject(ids, userId, opinion, true);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostReject");
//        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.新闻退稿", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("栏目管理.新闻退稿, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        if (Constants.REDIRECT_EDIT.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoedit.do";
        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
            ra.addAttribute("id", beans.iterator().next().getId());
            ra.addAttribute("position", position);
            return "redirect:infoview.do";
        } else {
            ra.addAttribute("returnUrl", returnUrl);
            ra.addAttribute("nodeFlag", nodeFlag);
            return "redirect:infolist.do";
        }
    }

    /**
     * 生成html
     * @param ids 新闻id集合
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     * @throws IOException
     * @throws TemplateException
     */
//    @RequiresPermissions("core:info:make_html")
    @RequestMapping("infomake_html.do")
    public String infomakeHtml(Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                           String queryStatus, HttpServletRequest request, RedirectAttributes ra) throws IOException,
            TemplateException {
        // 生成html是否要控制数据权限？不是非常必要。
        // User user = Context.getCurrentUser();
        // for (Integer id : ids) {
        // Info bean = query.get(id);
        // if (!bean.isDataPerm(user) || !bean.isAuditPerm(user)) {
        // throw new CmsException("accessDenied");
        // }
        // }
        Site site = Context.getCurrentSite();
        Integer userId=Context.getCurrentUserId();
        String ip = Servlets.getRemoteAddr(request);
        validateIds(ids, site.getId());
        for (Integer id : ids) {
            htmlService.makeInfo(id);
            logService.operation("栏目管理.新闻生成","（infomake_html）新闻生成静态数据", null,id, ip, userId, site.getId());
            logger.info("栏目管理.新闻生成, id={}.",id);
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        return "redirect:infolist.do";
    }

//    @RequiresPermissions("core:info:edit")
    @RequestMapping("infoview.do")
    public String infoview(Integer id, Integer position, Integer queryNodeId,
                       @RequestParam(defaultValue = "0") int queryNodeType, Integer queryInfoPermType, String queryStatus,
                       @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Info bean = infoQuery.get(id);
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Integer infoPermType = user.getInfoPermType(site.getId());
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(site.getId());
        RowSide<Info> side = infoQuery.findSide(site.getId(), mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, bean, position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);

        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute(OPRT, VIEW);
        return "core/publish_center/info_view";
    }

//    @RequiresPermissions("core:info:move_form")
    @RequestMapping("infomove_form.do")
    public String infomoveForm(Integer[] ids, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                           String queryStatus, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Integer siteId = site.getId();
        validateIds(ids, siteId);
//        Map<String,String[]> paramMap=new HashMap<String,String[]>();
//        paramMap.put("EQ_infoModel.flag",new String[]{Constants.MODEL_FLAG_DOC_NEWS});
//        paramMap.put("NOTEQ_nodeModel.flag",new String[]{Constants.SPECIAL_MANAGEMENT});
//        List<Node> nodeList=nodeQuery.findList(siteId,null, null, null,true, paramMap,null);
        List<Node> nodeList = nodeQuery.findList(siteId, null,null, true, null);
        List<Node> newsnodelist=new ArrayList<>();
        Set set = new  HashSet();
        if(nodeList!=null && nodeList.size()>0){
            for(Node node:nodeList){
                //文档类型为新闻的 排除专题 市州 栏目
                if(Constants.MODEL_FLAG_DOC_NEWS.equals(node.getInfoModel().getFlag())
                        && !Constants.SPECIAL_MANAGEMENT.equals(node.getNodeModel().getFlag())
                        && !Constants.SPECIAL_CATEGORY.equals(node.getNodeModel().getFlag())
                        && !Constants.SPECIAL_RECYCLE.equals(node.getNodeModel().getFlag())
                        && !Constants.MODEL_FLAG_CITY_DETAIL.equals(node.getNodeModel().getFlag())
                        && !Constants.MODEL_FLAG_CURRENTNEWS.equals(node.getNodeModel().getFlag())
                        && (node.getChildren()==null || node.getChildren().size()==0)){
                    for(Node n:node.getHierarchy()){
                        set.add(n);
                    }

                }

            }
        }
        newsnodelist.addAll(set);
        modelMap.addAttribute("ids", ids);
        modelMap.addAttribute("nodeList", newsnodelist);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        return "core/publish_center/info_move";
    }

//    @RequiresPermissions("core:info:move_submit")
    @RequestMapping("infomove_submit.do")
    public String infomoveSubmit(Integer[] ids, Integer nodeId, Integer queryNodeId, Integer queryNodeType,
                             Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());
        List<Info> beans = infoService.move(ids, nodeId);
//        if(ids!=null){
//            infoService.batchupdateHtmlThread(Arrays.asList(ids),false,"firePostMove");
//        }
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.新闻移动","移动到栏目nodeId："+nodeId+","+ bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("栏目管理.新闻移动, title={},nodeId={}.", bean.getTitle(),nodeId);
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        return "redirect:infolist.do";
    }

    @RequiresPermissions(value={
            "core:info:ref"
    },logical = Logical.OR)
    @RequestMapping("inforef.do")
    public String inforef(Integer[] ids, Integer id,Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                               String queryStatus, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Integer siteId = site.getId();
        if(ids==null && id!=null){
            ids=new Integer[]{id};
        }
        validateIds(ids, siteId);
        List<Node> nodeList = nodeQuery.findList(siteId, null,null, true, null);
        nodeList = user.getInfoPermList(siteId, nodeList);
        modelMap.addAttribute("ids", ids);
        modelMap.addAttribute("nodeList", nodeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        return "core/publish_center/info_choose_node";
    }

//    @RequiresPermissions("core:info:refsave")
    @RequestMapping("inforefsave.do")
    public String inforefsave(Integer[] ids, Integer nodeId, Integer queryNodeId, Integer queryNodeType,
                                 Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        validateIds(ids, site.getId());

        infoService.updateInfoRef(ids,nodeId,null);

        String ip = Servlets.getRemoteAddr(request);
        for (Integer id : ids) {
            Info bean=infoQuery.get(id);
            logService.operation("栏目管理.新闻引用", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("{} refsave Info, title={}.", bean.getTitle(),user.getId());

        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        return "redirect:infolist.do";
    }

//    @RequiresPermissions("core:info:focus:ref")
    @RequestMapping("focusRefInfo.do")
    public String focusRefInfo(Integer[] ids,Integer infoId,Integer orderId,Integer targetNodeId,
                               Integer queryNodeId, Integer queryNodeType,
                              Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        ids=new Integer[1];
        ids[0]=infoId;
        validateIds(ids, site.getId());

        infoService.updateInfoRef(ids,targetNodeId,orderId);

        String ip = Servlets.getRemoteAddr(request);
        for (Integer id : ids) {
            Info bean=infoQuery.get(id);
            logService.operation("栏目管理.焦点图引用保存", bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
            logger.info("{} focusRefInfo Info, title={}.", bean.getTitle(),user.getId());

        }

        ra.addAttribute("queryNodeId", targetNodeId);
        ra.addAttribute("orderId", orderId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("returnUrl", "core/publish_center/focus_list");
        ra.addAttribute("showInfoId", infoId);
        return "redirect:focuslist.do";
    }

    /**
     * 焦点图查询
     * @param queryNodeId 栏目id
     * @param queryNodeType
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param queryDate 查询日期
     * @param returnUrl 返回url
     * @param targetNodeId 目标栏目id
     * @param order 顺序
     * @param showInfoId
     * @param foucs 标记焦点图
     * @param tab 标记面板
     * @param pageable 分页对象
     * @param request  请求对象
     * @param modelMap
     * @return
     */
    @RequiresPermissions("core:info:focuslist")
    @RequestMapping("focuslist.do")
    public String focuslist(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,String queryDate,
                           String returnUrl,Integer targetNodeId,Integer order,Integer showInfoId,Integer foucs,String tab,
                           @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                           HttpServletRequest request, org.springframework.ui.Model modelMap) {
        String url=returnUrl;
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        String[] treeNumbers=null;
        if(treeNumber!=null){
            treeNumbers=new String[]{treeNumber.toString()};
        }
        Integer[] nodeIds=null;
        Integer[] modelIds=null;
        if(foucs!=null && foucs.intValue()==1){
               nodeId=null;
               queryStatus="A";
//               nodeIds=getNodeIdsByFlag(Constants.MODEL_FLAG_NEWS,siteId);
            //只查新闻类型的新闻
            Map<String,String[]> paramMap=new HashMap<String,String[]>();
            paramMap.put("EQ_flag",new String[]{Constants.MODEL_FLAG_DOC_NEWS});
            List<Model> modelList=modelService.findList(siteId,null,paramMap,null);
            if(modelList!=null && modelList.size()>0){
                modelIds=new Integer[modelList.size()];
               for(int i=0;i<modelList.size();i++){
                  modelIds[i]=modelList.get(i).getId();
               }
            }

        }

//        Date beginDate=null;
//        Date endDate=null;
        if(queryDate!=null){
            String startDate=Dates.formatDate(Dates.getOnedayStartDate(queryDate),"yyyy-MM-dd");
            DateTime dateTime=DateTime.parse(startDate).plusDays(1);
            String endDate=Dates.formatDate(dateTime.toDate(),"yyyy-MM-dd");
//            params.put("GTE_publishDate_Date",new String[]{startDate});
//            params.put("LT_publishDate_Date",new String[]{endDate});
        }

        boolean allInfoPerm = user.getAllInfoPerm(siteId);

        List<Attribute> attributeList = attributeService.findList(siteId);

        Page<Info> pagedList = infoQuery.findAll(modelIds,siteId, mainNodeId, nodeId, treeNumber, null, true,
                1, queryStatus, params, pageable,nodeIds);
//        Page<Info> pagedList = infoQuery.findPage(modelIds,nodeIds,null,
//                        null, null,new Integer[]{siteId},mainNodeId==null?null:new Integer[]{mainNodeId} ,null, null,
//                        null,treeNumbers, null, null, null,
//                        beginDate, endDate, null, null, null,
//                        null, null, null,queryStatus==null?null:new String[]{queryStatus},null, null,
//                        null, null, null, null, null, null, pageable);
        if(queryNodeId!=null){
            if(pagedList!=null && pagedList.getContent()!=null && pagedList.getContent().size()>0){
                for(Info bean:pagedList.getContent()){
                    if(bean!=null){
                        if(bean.getPriority()!=null && bean.getPriority().intValue()==4){
                            if(bean.getRefInfo()!=null){
                                Info info=bean.getRefInfo();
                                modelMap.addAttribute("live1", info);
                            }else if(bean.getRefLive()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefLive().getTitle());
                                detail.setSmallImage(bean.getRefLive().getImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live1", bean);
                            }else if(bean.getRefSpec()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefSpec().getTitle());
                                detail.setSmallImage(bean.getRefSpec().getSmallImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live1", bean);
                            }else{
                                modelMap.addAttribute("live1", bean);
                            }
                            modelMap.addAttribute("live1_id", bean.getId());
                        }else if(bean.getPriority()!=null && bean.getPriority().intValue()==3){
                            if(bean.getRefInfo()!=null){
                                Info info=bean.getRefInfo();
                                modelMap.addAttribute("live2", info);
                            }else if(bean.getRefLive()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefLive().getTitle());
                                detail.setSmallImage(bean.getRefLive().getImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live2", bean);
                            }else if(bean.getRefSpec()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefSpec().getTitle());
                                detail.setSmallImage(bean.getRefSpec().getSmallImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live2", bean);
                            }else{
                                modelMap.addAttribute("live2", bean);
                            }
                            modelMap.addAttribute("live2_id", bean.getId());
                        }else if(bean.getPriority()!=null && bean.getPriority().intValue()==2){
                            if(bean.getRefInfo()!=null){
                                Info info=bean.getRefInfo();
                                modelMap.addAttribute("live3", info);
                            }else if(bean.getRefLive()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefLive().getTitle());
                                detail.setSmallImage(bean.getRefLive().getImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live3", bean);
                            }else if(bean.getRefSpec()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefSpec().getTitle());
                                detail.setSmallImage(bean.getRefSpec().getSmallImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live3", bean);
                            }else{
                                modelMap.addAttribute("live3", bean);
                            }
                            modelMap.addAttribute("live3_id", bean.getId());
                        }else if(bean.getPriority()!=null && bean.getPriority().intValue()==1){
                            if(bean.getRefInfo()!=null){
                                Info info=bean.getRefInfo();
                                modelMap.addAttribute("live4", info);
                            }else if(bean.getRefLive()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefLive().getTitle());
                                detail.setSmallImage(bean.getRefLive().getImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live4", bean);
                            }else if(bean.getRefSpec()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefSpec().getTitle());
                                detail.setSmallImage(bean.getRefSpec().getSmallImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live4", bean);
                            }else{
                                modelMap.addAttribute("live4", bean);
                            }
                            modelMap.addAttribute("live4_id", bean.getId());
                        }else if(bean.getPriority()!=null && bean.getPriority().intValue()==0){
                            if(bean.getRefInfo()!=null){
                                Info info=bean.getRefInfo();
                                modelMap.addAttribute("live5",info);
                            }else if(bean.getRefLive()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefLive().getTitle());
                                detail.setSmallImage(bean.getRefLive().getImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live5", bean);
                            }else if(bean.getRefSpec()!=null){
                                InfoDetail detail=bean.getDetail();
                                detail.setTitle(bean.getRefSpec().getTitle());
                                detail.setSmallImage(bean.getRefSpec().getSmallImage());
                                bean.setDetail(detail);
                                modelMap.addAttribute("live5", bean);
                            }else{
                                modelMap.addAttribute("live5", bean);
                            }
                            modelMap.addAttribute("live5_id", bean.getId());
                        }
                    }
                }
            }
        }

        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node",queryNode);
        modelMap.addAttribute("returnUrl",returnUrl);
        modelMap.addAttribute("targetNodeId",targetNodeId);
        modelMap.addAttribute("order",order);
        modelMap.addAttribute("showInfoId",showInfoId);
        modelMap.addAttribute("foucs",foucs);
        modelMap.addAttribute("tab",tab);
        modelMap.addAttribute("queryDate",queryDate);
        return url;
    }

    /**
     * 查询直播（引用界面使用）
     * @param pageable 分页对象
     * @param queryNodeId 栏目id
     * @param order 顺序
     * @param returnUrl 返回url
     * @param tab 标记当前面板
     * @param queryDate 查询日期
     * @param targetNodeId 引用到栏目id
     * @param foucs 标记焦点图
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:chooselive:list")
    @RequestMapping("chooselivelist.do")
    public String chooselivelist(
            @PageableDefault(sort = "id",direction = Sort.Direction.DESC) Pageable pageable,
            Integer queryNodeId,Integer order,String returnUrl,String tab,String queryDate,
            Integer targetNodeId,Integer foucs,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        params.put("IN_status",new String[]{"1","2"});
        Page<LiveBroadcast> pagedList = liveBroadcastService.findAll(siteId, params, pageable);
        modelMap.addAttribute("livepagedList", pagedList);
        modelMap.addAttribute("queryNodeId",queryNodeId);
        modelMap.addAttribute("order",order);
        modelMap.addAttribute("tab",tab);
        modelMap.addAttribute("returnUrl",returnUrl);
        modelMap.addAttribute("targetNodeId",targetNodeId);
        modelMap.addAttribute("tab",tab);
        modelMap.addAttribute("foucs",foucs);
        modelMap.addAttribute("queryDate",queryDate);
        return returnUrl;
    }

    /**
     * 查询专题（引用界面使用）
     * @param pageable 分页对象
     * @param queryNodeId 栏目id
     * @param order 顺序
     * @param returnUrl 发挥url
     * @param tab 标记分页面板
     * @param targetNodeId 引用到栏目
     * @param foucs 标记焦点图
     * @param queryDate 查询日期
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:special:list")
    @RequestMapping("speclist.do")
    public String speclist(
            @PageableDefault(sort = {"priority", "creationDate"}, direction = Sort.Direction.DESC) Pageable pageable,
            Integer queryNodeId,Integer order,String returnUrl,String tab,
            Integer targetNodeId,Integer foucs,String queryDate,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        // 引用父专题 已发布
        params.put("EQ_level",new String[]{"0"}); //父专题
        params.put("EQ_publish",new String[]{"0"}); //已发布
        Page<Special> pagedList = specialService.findAll(siteId, params, pageable,0);

        List<SpecialCategory> categoryList = specialCategoryService
                .findList(siteId);
        modelMap.addAttribute("categoryList", categoryList);
        modelMap.addAttribute("specpagedList", pagedList);
        modelMap.addAttribute("queryNodeId",queryNodeId);
        modelMap.addAttribute("order",order);
        modelMap.addAttribute("tab",tab);
        modelMap.addAttribute("returnUrl",returnUrl);
        modelMap.addAttribute("targetNodeId",targetNodeId);
        modelMap.addAttribute("tab",tab);
        modelMap.addAttribute("foucs",foucs);
        modelMap.addAttribute("queryDate",queryDate);
        return returnUrl;
    }

    /**
     * 删除焦点新闻引用
     * @param ids
     * @param infoId 新闻id
     * @param orderId
     * @param targetNodeId 新闻所在栏目
     * @param queryNodeId 栏目id
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus
     * @param request
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:info:focus:delref")
    @RequestMapping("delfocusRefInfo.do")
    public String delfocusRefInfo(Integer[] ids,Integer infoId,Integer orderId,Integer targetNodeId,
                               Integer queryNodeId, Integer queryNodeType,
                               Integer queryInfoPermType, String queryStatus, HttpServletRequest request, RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        ids=new Integer[1];
        ids[0]=infoId;
        validateIds(ids, site.getId());
        Info sourceInfo=null;
        if(infoId!=null){
            sourceInfo=infoQuery.get(infoId);
            if(sourceInfo!=null){
                infoNodeService.deleteByNodeIdAndInfoId(targetNodeId,infoId);
                List<Info> infos=infoService.delete(ids);
//        infoService.batchupdateHtmlThread(Arrays.asList(ids),true,"firePostDelete");
                String ip = Servlets.getRemoteAddr(request);
                if(infos!=null){
                    for (Info bean : infos) {
                        logService.operation("栏目管理.删除引用","栏目："+bean.getNode().getName()+","+bean.getTitle(), null, bean.getId(), ip, user.getId(), site.getId());
                        logger.info("{} delfocusRefInfo Info, title={}.", bean.getTitle(),user.getId());

                    }
                }
            }
        }
        ra.addAttribute("queryNodeId", targetNodeId);
        ra.addAttribute("orderId", orderId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("returnUrl", "core/publish_center/focus_list");
        ra.addAttribute("showInfoId", infoId);
        return "redirect:focuslist.do";
    }

//    @RequiresPermissions("core::focus:info:create")
    @RequestMapping("focusinfocreate.do")
    public String focusinfocreate(Integer id, Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType,
                             Integer refInfoId, @RequestParam(defaultValue = "0")Integer type,Integer order,
                             String queryStatus, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        if (id != null) {
            Info bean = infoQuery.get(id);
            Backends.validateDataInSite(bean, site.getId());
            modelMap.addAttribute("bean", bean);
        }
        Node node;
        if (queryNodeId == null) {
            node = nodeQuery.findRoot(site.getId());
            if (node == null) {
                throw new CmsException("info.error.nodeNotFound");
            }
        } else {
            node = nodeQuery.get(queryNodeId);
        }
        if(refInfoId!=null){
            Info refInfo=infoQuery.get(refInfoId);
            modelMap.addAttribute("refInfo", refInfo);
        }
        Backends.validateDataInSite(node, site.getId());
        Model model = node.getInfoModel();
        List<Attribute> attrList = attributeService.findList(site.getId());
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();
        modelMap.addAttribute("model", model);
        modelMap.addAttribute("node", node);
        modelMap.addAttribute("attrList", attrList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute(OPRT, CREATE);
        modelMap.addAttribute("order", order);
        modelMap.addAttribute("type",type);
        return "core/publish_center/focus_form";
    }

    /**
     * 焦点图引用
     * @param bean 新闻主数据对象
     * @param detail 新闻详情数据对象
     * @param nodeIds 栏目id集合
     * @param specialIds 专题id集合
     * @param viewGroupIds 浏览权限（预留参数）
     * @param viewOrgIds
     * @param attrIds 属性
     * @param nodeId 栏目id
     * @param tagKeywords 关键词
     * @param order 优先级
     * @param draft 草稿
     * @param imagesName 图片集名称
     * @param imagesText 图片集文本
     * @param imagesImage 图片集
     * @param filesName 文件集名称
     * @param filesFile 文件集
     * @param filesLength 文件集大小
     * @param redirect
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param refInfoId 引用新闻
     * @param refSpecId 引用专题
     * @param refLiveId 引用直播
     * @param returnUrl 返回url
     * @param queryDate 查询日期
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:focus:info:save")
    @RequestMapping("focusinfosave.do")
    public String focusinfosave(Info bean, InfoDetail detail, Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds,
                           Integer[] viewOrgIds, Integer[] attrIds, Integer nodeId, String tagKeywords,Integer order,
                           @RequestParam(defaultValue = "false") boolean draft, String[] imagesName, String[] imagesText,
                           String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, String redirect,
                           Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                           Integer refInfoId,Integer refSpecId,Integer refLiveId,String returnUrl,String queryDate,
                           HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesText[i])
                        || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        //引用文章
        if(refInfoId!=null){
            Info refInfo=infoQuery.get(refInfoId);
            detail.setTitle(refInfo.getTitle());
            bean.setRefInfo(refInfo);
            bean.setPublishDate(Dates.formatDateStr(queryDate,null));
            if(order!=null){
                bean.setPriority(order);
            }

        }
        //引用专题
        boolean isSave=true;
        if(refSpecId!=null){
            Special refSpec=specialService.get(refSpecId);
            if(refSpec.getParent()!=null){ //不是父专题
                ra.addFlashAttribute(MESSAGE, SPEC_NOT_PARENT);
                isSave=false;
            }
            if(refSpec.getPublish()!=null && refSpec.getPublish().intValue()==1){ //未发布
                ra.addFlashAttribute(MESSAGE, SPEC_NOT_PUBLISH);
                isSave=false;
            }
            detail.setTitle(refSpec.getTitle());
            bean.setRefSpec(refSpec);
            bean.setPriority(order);
        }
        //引用直播
        if(refLiveId!=null){
            LiveBroadcast live=liveBroadcastService.get(refLiveId);
            bean.setNewsType(5);   //直播新闻
            bean.setRefLive(live);
            detail.setTitle(live.getTitle());
            if(order!=null){
                bean.setPriority(order);
            }
        }
        String status = draft ? Info.DRAFT : null;
        bean.setStatus("A"); //正常，已发布
        if(order!=null && isSave){
            Limitable limitable =new LimitRequest(0,99999, Sort.Direction.DESC,"publishDate");
            List<Info> list = infoQuery.findList(null,new Integer[]{nodeId}, null,
                    null, null,new Integer[]{siteId} , null,null, null,
                    null, null, null, null,new Integer[]{order},
                    null, null, null, null,null,
                    null, null, null, null,null, null,
                    null, null, null, null, null, null, limitable,null);
            if(list!=null && list.size()>0){
                ra.addFlashAttribute(MESSAGE,DATA_EXIST);
            }else{
                Info result=infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,null, customs, clobs, images, files,
                        attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
                String ip = Servlets.getRemoteAddr(request);
                logService.operation("栏目管理.添加引用", "栏目："+bean.getNode().getName()+","+bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("save Info, title={}.", bean.getTitle());
                ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
            }
        }else if(isSave){

            Info result=infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,null, customs, clobs, images, files,
                    attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
            String ip = Servlets.getRemoteAddr(request);
            logService.operation("栏目管理.添加引用", "栏目："+bean.getNode().getName()+","+bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("save Info, title={}.", bean.getTitle());
            ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        }

        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("id", bean.getId());
        ra.addAttribute("returnUrl","core/publish_center/focus_list");
        ra.addAttribute("queryDate",queryDate);
        if(returnUrl==null){
            returnUrl="focuslist.do";
        }else{
            ra.addAttribute("returnUrl","core/current_hour/hour_list");
        }
        return "redirect:"+returnUrl;
    }

    /**
     * 焦点图 互换位置
     * @param infoId 新闻id
     * @param newInfoId （另外一个或者空）新闻id
     * @param order 顺序
     * @param newOrder （另外一个）顺序
     * @param response
     * @param request
     */
//    @RequiresPermissions("core:focus:info:updateOrder")
    @RequestMapping("updateOrder.do")
    public void updateOrder(Integer infoId, Integer newInfoId,Integer order,Integer newOrder,HttpServletResponse response,HttpServletRequest request) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        String ip = Servlets.getRemoteAddr(request);
        if(infoId!=null && newInfoId!=null){
            Info info=infoQuery.get(infoId);
            Info newInfo=infoQuery.get(newInfoId);
            if(info!=null && newInfo!=null){
                infoService.updateOrder(newInfo.getPriority(),info.getId());
                infoService.updateOrder(info.getPriority(),newInfo.getId());
                htmlService.makeNode(info.getNode(),null);
                logService.operation("栏目管理.焦点图拖动排位", info.getTitle()+","+newInfo.getTitle(),null,info.getId(), ip, userId, siteId);
            }
        }else if(infoId!=null){
            Info info=infoQuery.get(infoId);
            if(info!=null){
                infoService.updateOrder(newOrder,infoId);
                htmlService.makeNode(info.getNode(),null);
                logService.operation("栏目管理.焦点图拖动排位",info.getTitle(),null,info.getId(), ip, userId, siteId);
            }

        }else if(newInfoId!=null){
            Info info=infoQuery.get(newInfoId);
            if(info!=null){
                infoService.updateOrder(order,newInfoId);
                htmlService.makeNode(info.getNode(),null);
                logService.operation("栏目管理.焦点图拖动排位", info.getTitle(),null,info.getId(), ip, userId, siteId);
            }
        }
        Servlets.writeHtml(response, "true");
    }

    /**
     * 动态审核通过
     * @param ids 动态id
     * @param opinion
     * @param position
     * @param queryNodeId 栏目id
     * @param queryParentId
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
//    @RequiresPermissions("core:info:audit_pass")
    @RequestMapping("dynamicauditPass.do")
    public String dynamicauditPass(Integer[] ids, String opinion, Integer position, Integer queryNodeId,Integer queryParentId,
                                Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                                HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.pass(ids, userId, opinion);
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.动态审核通过", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("dynamicauditPass, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        if (Constants.REDIRECT_EDIT.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:infoedit.do";
//        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:infoview.do";
//        } else {
//            return "redirect:dynamiclnfolist.do";
//        }
        return "redirect:dynamiclnfolist.do";
    }

    /**
     * 动态撤销审核
     * @param ids 动态id
     * @param opinion
     * @param position
     * @param queryNodeId 栏目id
     * @param queryParentId
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    //    @RequiresPermissions("core:info:audit_reject")
    @RequestMapping("dynamicauditReject.do")
    public String dynamicauditReject(Integer[] ids, String opinion, Integer position, Integer queryNodeId,Integer queryParentId,
                                  Integer queryNodeType, Integer queryInfoPermType, String queryStatus, String redirect,
                                  HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        validateIds(ids, siteId);
        List<Info> beans = infoService.reject(ids, userId, opinion, false);
        String ip = Servlets.getRemoteAddr(request);
        for (Info bean : beans) {
            logService.operation("栏目管理.动态撤销审核", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("dynamicauditReject, title={}.", bean.getTitle());
        }
        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryParentId", queryParentId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        if (Constants.REDIRECT_EDIT.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:infoedit.do";
//        } else if (Constants.REDIRECT_VIEW.equals(redirect)) {
//            ra.addAttribute("id", beans.iterator().next().getId());
//            ra.addAttribute("position", position);
//            return "redirect:infoview.do";
//        } else {
//            return "redirect:infolist.do";
//        }
        return "redirect:dynamiclnfolist.do";
    }

    /**
     * 栏目管理，生成栏目页
     * @param request 请求对象
     * @param queryParentId 栏目（可能上级，看页面具体作用）id
     * @param showDescendants 显示子栏目
     * @param returnUrl 返回url
     * @param ra
     * @return 结果页面
     */
    @RequiresPermissions("core:generation:nodeHome")
    @RequestMapping("generationNodeHome.do")
    public String generationNodeHome(HttpServletRequest request,Integer queryParentId,
                                    @RequestParam(defaultValue = "true") boolean showDescendants,String returnUrl,
                                    RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
//        Node node = nodeQuery.findRoot(siteId);
        Node node=nodeQuery.get(queryParentId);
        if (node != null) {
            htmlService.makeNode(node.getId());
            logService.operation("栏目管理.生成栏目页", node.getName(), null, node.getId(), request);
            logger.info("generationNodeHome. name={}", node.getName());
        }
        ra.addAttribute("queryParentId",queryParentId);
        ra.addAttribute("showDescendants",showDescendants);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("returnUrl",returnUrl);
        return "redirect:nodelist.do";
    }

    /**
     * 修改栏目是否发布
     * @param request 请求对象
     * @return 成功失败json数据
     */
    @RequiresPermissions("core:node:updateNodePublish")
    @RequestMapping(value = "updateNodePublish.do",produces ="application/json; charset=utf-8")
    @RequiresRoles("super")
    public  @ResponseBody
    String updateNodePublish(HttpServletRequest request) {
        String msg="success";
        Map map = RequestUtils.getRequest(request);
        String nodeId=(String)map.get("nodeId");
        String publish=(String)map.get("publish");
        if(nodeId!=null && StringUtils.isNotBlank(publish)){
            service.updatePublish(Integer.valueOf(nodeId),publish);
            logService.operation("栏目管理.修改栏目发布状态","栏目id:"+nodeId+",状态(0发布1未发布)："+publish, null, Integer.valueOf(nodeId), request);
        }else{
             msg="error";
        }

        JSONObject json = new JSONObject();
        JSONObject jsons = new JSONObject();
        jsons.put("msg",msg);
        return jsons.toJSONString();
    }

    /**
     * 修改优先级
     * @param priority 优先级
     * @param infoId 新闻id
     * @param request 请求对象
     * @return 成功失败json数据
     */
    @RequestMapping("updatePriority.do")
//    @RequiresRoles("super")
//    @RequiresPermissions("core:info:updatePriority")
    @ResponseBody
    public String updatePriority(Integer priority,Integer infoId,
                                       HttpServletRequest request) {
        String msg="success";
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        String ip = Servlets.getRemoteAddr(request);
        if(infoId!=null && priority!=null){
            infoService.updateOrder(priority,infoId);
            logService.operation("栏目管理.设置优先级","优先级为："+priority.toString(),null,infoId, ip, user.getId(), site.getId());
            logger.info("updatePriority,id={},priority={}.",infoId,priority);
        }
        JSONObject json = new JSONObject();
        JSONObject jsons = new JSONObject();
        jsons.put("msg",msg);
        return jsons.toJSONString();
    }


    /**
     * 活动栏目新闻保存
     * @param bean 新闻主数据对象
     * @param detail 新闻详情数据对象
     * @param nodeIds 栏目id集合
     * @param specialIds 专题id集合
     * @param viewGroupIds 浏览权限（预留参数）
     * @param viewOrgIds
     * @param attrIds 属性
     * @param nodeId 栏目id
     * @param tagKeywords 关键词
     * @param order 优先级
     * @param draft 草稿
     * @param imagesName 图片集名称
     * @param imagesText 图片集文本
     * @param imagesImage 图片集
     * @param filesName 文件集名称
     * @param filesFile 文件集
     * @param filesLength 文件集大小
     * @param redirect
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param refInfoId 引用新闻
     * @param refSpecId 引用专题
     * @param refLiveId 引用直播
     * @param returnUrl 返回url
     * @param queryDate 查询日期
     * @param request 请求对象
     * @param ra
     * @return 结果页面
     */
///    @RequiresPermissions("core:activity:info:save")
    @RequestMapping("activityinfosave.do")
    public String activityinfosave(Info bean, InfoDetail detail, Integer[] nodeIds, Integer[] specialIds, Integer[] viewGroupIds,
                                Integer[] viewOrgIds, Integer[] attrIds, Integer nodeId, String tagKeywords,Integer order,
                                @RequestParam(defaultValue = "false") boolean draft, String[] imagesName, String[] imagesText,
                                String[] imagesImage, String[] filesName, String[] filesFile, Long[] filesLength, String redirect,
                                Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                                Integer refInfoId,Integer refSpecId,Integer refLiveId,String returnUrl,String queryDate,
                                HttpServletRequest request, RedirectAttributes ra) {
        returnUrl="infolist.do";
        Integer siteId = Context.getCurrentSiteId();
        Integer userId = Context.getCurrentUserId();
        Map<String, String> customs = Servlets.getParamMap(request, "customs_");
        Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
        if (StringUtils.isBlank(detail.getMetaDescription())) {
            String title = detail.getTitle();
            detail.setMetaDescription(Info.getDescription(clobs, title));
        }
        String[] tagNames = splitTagKeywords(tagKeywords);
        Map<String, String> attrImages = Servlets.getParamMap(request, "attrImages_");
        for (Map.Entry<String, String> entry : attrImages.entrySet()) {
            entry.setValue(StringUtils.trimToNull(entry.getValue()));
        }
        List<InfoImage> images = new ArrayList<InfoImage>();
        if (imagesName != null) {
            InfoImage infoImage;
            for (int i = 0, len = imagesName.length; i < len; i++) {
                if (StringUtils.isNotBlank(imagesName[i]) || StringUtils.isNotBlank(imagesText[i])
                        || StringUtils.isNotBlank(imagesImage[i])) {
                    infoImage = new InfoImage(imagesName[i], imagesText[i], imagesImage[i]);
                    images.add(infoImage);
                }
            }
        }
        List<InfoFile> files = new ArrayList<InfoFile>();
        if (filesName != null) {
            InfoFile infoFile;
            for (int i = 0, len = filesFile.length; i < len; i++) {
                if (StringUtils.isNotBlank(filesName[i]) && StringUtils.isNotBlank(filesFile[i])) {
                    infoFile = new InfoFile(filesName[i], filesFile[i], filesLength[i]);
                    files.add(infoFile);
                }
            }
        }
        //引用文章
        if(refInfoId!=null){
            Info refInfo=infoQuery.get(refInfoId);
            detail.setTitle(refInfo.getTitle());
            bean.setRefInfo(refInfo);
            bean.setPublishDate(refInfo.getPublishDate());
            if(order!=null){
                bean.setPriority(order);
            }

        }
        //引用专题
        boolean isSave=true;
        if(refSpecId!=null){
            Special refSpec=specialService.get(refSpecId);
            if(refSpec.getParent()!=null){ //不是父专题
                ra.addFlashAttribute(MESSAGE, SPEC_NOT_PARENT);
                isSave=false;
            }
            if(refSpec.getPublish()!=null && refSpec.getPublish().intValue()==1){ //未发布
                ra.addFlashAttribute(MESSAGE, SPEC_NOT_PUBLISH);
                isSave=false;
            }
            detail.setTitle(refSpec.getTitle());
            bean.setRefSpec(refSpec);
            bean.setNewsType(4);   //专题
            bean.setPriority(order);
        }
        //引用直播
        if(refLiveId!=null){
            LiveBroadcast live=liveBroadcastService.get(refLiveId);
            bean.setNewsType(5);   //直播新闻
            bean.setRefLive(live);
            detail.setTitle(live.getTitle());
            if(order!=null){
                bean.setPriority(order);
            }
        }
        String status = draft ? Info.DRAFT : null;
        bean.setStatus("A"); //正常，已发布
        if(order!=null && isSave){
            Limitable limitable =new LimitRequest(0,99999, Sort.Direction.DESC,"publishDate");
            List<Info> list = infoQuery.findList(null,new Integer[]{nodeId}, null,
                    null, null,new Integer[]{siteId} , null,null, null,
                    null, null, null, null,new Integer[]{order},
                    null, null, null, null,null,
                    null, null, null, null,null, null,
                    null, null, null, null, null, null, limitable,null);
            if(list!=null && list.size()>0){
                ra.addFlashAttribute(MESSAGE,DATA_EXIST);
            }else{
                Info result=infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,null, customs, clobs, images, files,
                        attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
                String ip = Servlets.getRemoteAddr(request);
                logService.operation("活动栏目.新增专题", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
                logger.info("activity save Info, title={}.", bean.getTitle());
                ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
            }
        }else if(isSave){

            Info result=infoService.save(bean, detail, nodeIds, specialIds, viewGroupIds, viewOrgIds,null, customs, clobs, images, files,
                    attrIds, attrImages, tagNames, nodeId, userId, status, siteId);
            String ip = Servlets.getRemoteAddr(request);
            logService.operation("活动栏目.新增专题", bean.getTitle(), null, bean.getId(), ip, userId, siteId);
            logger.info("activity save Info, title={}.", bean.getTitle());
            ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        }

        ra.addAttribute("queryNodeId", queryNodeId);
        ra.addAttribute("queryNodeType", queryNodeType);
        ra.addAttribute("queryInfoPermType", queryInfoPermType);
        ra.addAttribute("queryStatus", queryStatus);
        ra.addAttribute("id", bean.getId());
        ra.addAttribute("returnUrl","info_activity_list");
        ra.addAttribute("queryDate",queryDate);

        return "redirect:"+returnUrl;
    }

    /**
     * 修改发布时间（活动栏目）
     * @param request 请求对象
     * @param queryNodeId 栏目id
     * @param infoId 新闻id
     * @param pubTime 发布时间
     * @param ra 重定向对象
     * @return 结果页面
     */
//    @RequiresPermissions("core:activity:updatePubTime")
    @RequestMapping("updatePubTime.do")
    public String updatePubTime(HttpServletRequest request,Integer queryNodeId,Integer infoId,String pubTime,
                                RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        if(infoId!=null && StringUtils.isNotBlank(pubTime)){
            Date date=Dates.formatDateStr(pubTime,"yyyy-MM-dd HH:mm:ss");
            infoService.updatePublishDate(infoId,date);
            logService.operation("opr.activitynode.updatePubTime",pubTime, null,infoId, request);
            logger.info("updatePubTime infoId={}, pubTime={}",infoId,pubTime);
        }
        ra.addAttribute("queryNodeId",queryNodeId);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("returnUrl","info_activity_list");
        return "redirect:infolist.do";
    }

    /**
     * 修改动态是否精选
     * @param dynamicId 动态id
     * @param select 精选与否
     * @param request 请求对象
     * @return json结果
     */
    @RequestMapping("updateDynamicSelect.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:info:updateDynamicSelect")
    @ResponseBody
    public String updateDynamicSelect(Integer dynamicId,Integer select,
                                 HttpServletRequest request) {
        String msg="fail";
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        String ip = Servlets.getRemoteAddr(request);
        if(dynamicId!=null && select!=null){
            Info info=infoQuery.get(dynamicId);
            if(info!=null){
                infoService.updateSelect(select,dynamicId);
                msg="success";
            }
            logService.operation("修改主播动态是否精选","修改主播动态为(0是1否):"+select, select.toString(),dynamicId, ip, user.getId(), site.getId());
            logger.info("updateDynamicSelect,dynamicId={},select={}.",dynamicId,select);
        }
        JSONObject json = new JSONObject();
        json.put("msg",msg);
        return json.toJSONString();
    }

    @ModelAttribute
    public void preloadNodeBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Node bean = nodeQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("nodebean", bean);
                NodeDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new NodeDetail();
                    detail.setId(oid);
                    detail.setNode(bean);
                }
                modelMap.addAttribute("nodedetail", detail);
            }
        }
    }

    @ModelAttribute
    public void preloadInfoBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Info bean = infoQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                InfoDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new InfoDetail();
                    detail.setId(oid);
                    detail.setInfo(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

	private void validateIds(Integer[] ids, Integer siteId) {
		for (Integer id : ids) {
			Backends.validateDataInSite(nodeQuery.get(id), siteId);
		}
	}

	private Integer[] getInfoPermIds(Integer siteId, Integer parentId) {
		Collection<Role> roles = null;
		if (parentId != null) {
			Node node = nodeQuery.get(parentId);
			if (node != null) {
				roles = node.getInfoPerms();
			}
		}
		if (roles == null) {
			roles = roleService.findList(siteId);
		}
		int len = roles.size();
		Integer[] ids = new Integer[len];
		int i = 0;
		for (Role role : roles) {
			ids[i++] = role.getId();
		}
		return ids;
	}

	private Integer[] getNodePermIds(Integer siteId, Integer parentId) {
		Collection<Role> roles = null;
		if (parentId != null) {
			Node node = nodeQuery.get(parentId);
			if (node != null) {
				roles = node.getNodePerms();
			}
		}
		if (roles == null) {
			roles = roleService.findList(siteId);
		}
		int len = roles.size();
		Integer[] ids = new Integer[len];
		int i = 0;
		for (Role role : roles) {
			ids[i++] = role.getId();
		}
		return ids;
	}

	private Integer[] getViewGroupIds(Integer siteId, Integer parentId) {
		Collection<MemberGroup> groups = null;
		if (parentId != null) {
			Node node = nodeQuery.get(parentId);
			if (node != null) {
				groups = node.getViewGroups();
			}
		}
		if (groups == null) {
			groups = memberGroupService.findList();
		}
		int len = groups.size();
		Integer[] ids = new Integer[len];
		int i = 0;
		for (MemberGroup group : groups) {
			ids[i++] = group.getId();
		}
		return ids;
	}

	private Integer[] getContriGroupIds(Integer siteId, Integer parentId) {
		Collection<MemberGroup> groups = null;
		if (parentId != null) {
			Node node = nodeQuery.get(parentId);
			if (node != null) {
				groups = node.getContriGroups();
			}
		}
		if (groups == null) {
			groups = memberGroupService.findList();
		}
		int len = groups.size();
		Integer[] ids = new Integer[len];
		int i = 0;
		for (MemberGroup group : groups) {
			ids[i++] = group.getId();
		}
		return ids;
	}

	private Integer[] getCommentGroupIds(Integer siteId, Integer parentId) {
		Collection<MemberGroup> groups = null;
		if (parentId != null) {
			Node node = nodeQuery.get(parentId);
			if (node != null) {
				groups = node.getCommentGroups();
			}
		}
		if (groups == null) {
			groups = memberGroupService.findList();
		}
		int len = groups.size();
		Integer[] ids = new Integer[len];
		int i = 0;
		for (MemberGroup group : groups) {
			ids[i++] = group.getId();
		}
		return ids;
	}
    private String[] splitTagKeywords(String tagKeywords) {
        String split = Constants.TAG_KEYWORDS_SPLIT;
        if (StringUtils.isNotBlank(split)) {
            for (int i = 0, len = split.length(); i < len; i++) {
                tagKeywords = StringUtils.replace(tagKeywords, String.valueOf(split.charAt(i)), ",");
            }
        }
        return StringUtils.split(tagKeywords, ',');
    }

    private Integer[] getNodeIdsByFlag(String modelFlag,Integer siteId) {
        Integer [] nodeIds=null;
        Map<String,String[]> paramMap=new HashMap<String,String[]>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        paramMap=new HashMap<String,String[]>();
        String[] idsStr;
        if(models!=null && models.size()>0){
            idsStr=new String[models.size()];
            for(int i=0;i<models.size();i++){
                idsStr[i]=models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id",idsStr);
        }
        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList=nodeQuery.findList(siteId,null,
                null,null,true,
                paramMap, paramSort);
        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];
            for(int i=0;i<currentNodeList.size();i++){
                nodeIds[i]=(currentNodeList.get(i).getId());
            }
        }
        return  nodeIds;
    }

    // 通过栏目模型id获取栏目
    private Map getFlagByNodeIds(String modelFlag,Integer siteId) {
        // 返回参数
        Map<String,Object> returnMap = new HashMap();
        JSONArray columns = new JSONArray();
        Integer [] nodeIds=null;

        Map<String,String[]> paramMap=new HashMap<>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        if (models == null || models.size() ==0){
            return  null;
        }

        String[] ids = new String[models.size()];
        String[] nodeNames = new String[models.size()];
        for(int i=0;i<models.size();i++){
            ids[i]=models.get(i).getId().toString();
            nodeNames[i]=models.get(i).getName();
        }
        paramMap=new HashMap<>();
        paramMap.put("EQ_nodeModel.id",ids);

        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList = nodeQuery.findList(siteId,null, null,null,true, paramMap, paramSort);

        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];

            for(int i=0;i<currentNodeList.size();i++){
                String name = currentNodeList.get(i).getName();

                for (int j=0;j<nodeNames.length;j++){
                    if (!name.equals(nodeNames[j])){
                        JSONObject node = new JSONObject();
                        node.put("id",currentNodeList.get(i).getId());
                        node.put("name",currentNodeList.get(i).getName());

                        nodeIds[i]=(currentNodeList.get(i).getId());
                        columns.add(node);
                    }
                }
            }
        }
        returnMap.put("nodes",columns);
        returnMap.put("nodeIds",nodeIds);
        return  returnMap;
    }

    private String getAnchorsJosnStr(Site site){
        //查询主播的父级栏目
        Integer [] nodeIds=getNodeIdsByFlag(Constants.MODEL_FLAG_ANCHOR_DYNAMIC,site.getId());
        Integer parentId=null;
        if(nodeIds!=null && nodeIds.length>0){
            parentId=nodeIds[0];
        }
        List<Node> list = nodeQuery.findList(site.getId(), parentId,null, true, null);
        List<Node> removeList=new ArrayList<Node>();
        JSONArray jsonArray=new JSONArray();
        JSONObject anchor=null;
        for(Node n:list){
            if(!Constants.MODEL_FLAG_ANCHOR_DYNAMIC.equals(n.getNodeModel().getFlag())){
                anchor=new JSONObject();
                anchor.put("id",n.getId());
                anchor.put("text",n.getName());
                jsonArray.add(anchor);
            }
        }
        String stringjson = JSON.toJSONString(jsonArray, SerializerFeature.WriteMapNullValue);
        return  stringjson;
    }
    private String getCityNodesJosnStr(Site site){
        //查询市州的父级栏目
        Integer [] nodeIds=getNodeIdsByFlag(Constants.MODEL_FLAG_CITY_STATE,site.getId());
        Integer parentId=null;
        if(nodeIds!=null && nodeIds.length>0){
            parentId=nodeIds[0];
        }
        List<Node> list = nodeQuery.findList(site.getId(), parentId,null, true, null);
        List<Node> removeList=new ArrayList<Node>();
        JSONArray jsonArray=new JSONArray();
        JSONObject city=null;
        for(Node n:list){
            if(!Constants.MODEL_FLAG_CITY_STATE.equals(n.getNodeModel().getFlag())){
                city=new JSONObject();
                city.put("id",n.getId());
                city.put("text",n.getName());
                jsonArray.add(city);
            }
        }
        String stringjson = JSON.toJSONString(jsonArray, SerializerFeature.WriteMapNullValue);
        return  stringjson;
    }


	@Autowired
	private OperationLogService logService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MemberGroupService memberGroupService;
	@Autowired
	private WorkflowService workflowService;
	@Autowired
	private ModelService modelService;
	@Autowired
	private NodeService service;
	@Autowired
	private NodeQueryService nodeQuery;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private InfoQueryService infoQuery;
    @Autowired
    private InfoService infoService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private InfoNodeService infoNodeService;
    @Autowired
    private LiveBroadcastService liveBroadcastService;
    @Autowired
    private SpecialCategoryService specialCategoryService;
    @Autowired
    private SpecialService specialService;
    @Autowired
    private HtmlGenerator htmlGenerator;
    @Autowired
    private InfoFulltextService infoFulltextService;
    @Autowired
    private UserMemberGroupService userMemberGroupService;
    @Autowired
    private UserService userService;

}
